I received valuable assistance for a previous issue at: "TypeError.parent.context.car.getBrands is not a function": s, which is closely related to my current question. The root of the problem lies in the fact that my application fails to function unless I create a new instance of "car" and then call the method:
getById(id: string) {
return this.http.get('app/car.json'+id)
/*
if I log the incoming data here to the console,
the correct data from server comes, e.g. 'id: id, name: name, brands: Array[2]'
*/
.map(data => data.json())
.map(car => new Car(car.id, car.name)); //<== this line causes problem!
}
The component receiving the data looks like this:
routerOnActivate(curr: RouteSegment): void {
let id = curr.getParam('id');
this._service.getById(id)
.subscribe(car => {
// This code executes upon receiving the server response
this.car = car;
console.log("res: ", this.car); // <=== correct car without the array of brands
});
// Code here is executed before the server response despite being written below
}
When a new instance of "Car" is created, it contains an empty Array of Brands.
This is how my service is structured:
@Injectable()
export class Service {
constructor(private http: Http) { }
getCars(){
return this.http.get...
}
getById(id: string) {
return this.http.get...
}
}
And here is how my Car class is defined:
export class Car {
private brands: Array<Brand>;
constructor(public id: string, public name: string) {
this.brands = new Array<Brand>();
}
public getBrands(): Array<Brand> {
return this.brands;
}
// Some other methods.
}
Even though there is data in the brands Array, the getById method only retrieves the id and name parameter, leaving the brands array empty. I am uncertain about how to retrieve the data from the server while including the array of brands!
I have tried creating a Car object within my service, which logs the correct data but does not effectively work.
getById(id: string) {
this.http.get('app/car.json'+id)
.map((res: Response) => res.json())
.subscribe(car => {
// This code is executed when the server response arrives
this.car = car;
console.log("res: ", this.car); // <==== correct data!
return this.car;
});
// Placing return this.car here doesn't give a void error, but results in an undefined car due to premature execution before subscribe!
}
When attempting to receive the data in the component:
routerOnActivate(curr: RouteSegment){
let id = curr.getParam('id');
this.car = this._service.getById(id); // Error: Type 'void' is not assignable to type 'Car'
}
Any guidance would be greatly appreciated! Thank you!