The problem is as follows, through a service ( ModeloService
), I get an array of Modelo
, where Modelo
is a class, I happen to be unable to access the methods of this class, since cast
in the service is not being done correctly, instead of cast
being done to array
Modelo
, only one array of a normal javascript object, however, typed with Modelo
. >
% injected% is http
.
Follow the code with the classes mentioned:
I have the following class Angular2
, which represents a template (domain):
export class Modelo{
id: number;
type: string;
size: number;
constructor() {
}
public allowSize(): boolean {
return this.type != null && (this.type.toLowerCase() == 'size');
}
}
And the following service:
@Injectable()
export class ModeloService {
constructor(private http: Http) {
}
getAll(): Observable<Modelo[]> {
return this.http.get(myEnvironment.MODELO_SERVICE_PATH)
.map(res => <Modelo[]> res.json());
}
}
When trying to use this TypeScript
method, I get the following error: allowSize()
modeloService.getAll()
.subscribe(array=> array.forEach(modelo => console.log(modelo.allowSize())),
error => console.log(error));
When I start ERROR TypeError: modelo.allowSize is not a function
in the console, I do not get a modelo
object, I only get a normal javascript object with key and values:
{id: 1; type: 'size'; size: '10'}
The way I found to solve the problem was to create the object, as follows:
getAll(): Observable<Modelo[]> {
return this.http.get(myEnvironment.MODELO_SERVICE_PATH)
.map(res => {
return (<Modelo[]> res.json()).map(modelo => {
let modeloToReturn = new Modelo();
modeloToReturn.id = modelo.id;
modeloToReturn.type= modelo.type;
modeloToReturn.size = modelo.size;
return modeloToReturn;
})
});
}
Resolve, but it causes another problem that I have to keep evolving this service whenever I evolve my model, is not there a way to do this cast automatically?