“TypeError.parent.context.car.getBrands is not a f

2019-03-06 03:31发布

问题:

Service:

@Injectable()
export class Service {

    constructor(private http: Http) { }

    getCars(){
        return this.http.get...       
    }

    getById(id: string) {
        return this.http.get...       
    }    
}

Car class:

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.
}

Then I have a Brand class (object) with it's own attributes and methods and so on and and so on...

car.list.component:

@Component({
    selector: 'car-list',
    template: `
    //some more code here
    <table>
        <tr *ngFor="let car of cars" >
        <td>{{car.name}}</td>
        <td><button (click)="goToDetail(car)">Detail</button></td>
        </tr>
    </table>
  `,
})


export class ListComponent implements OnActivate {
    id: string
    name: string;
    cars: Array<Car>

    constructor(public _service: Service, public _router: Router) {   }

    routerOnActivate(): void {
        this._service.getCars()
            .subscribe(cars => this.cars = cars);
    }
 }

And then the problem, the car.detail.component:

@Component({
    selector: 'car-detail',
    template: `  
    <h1>Car: {{car?.name}}</h1>
    <hr>
    <div *ngFor="let brand of car?.getBrands(); let i=index">  
        <h2>Brand {{i+1}}</h2>
    </div>   

`,
})

export class DetailComponent implements OnActivate {

    @Input() car: Car;

    constructor(public _service: Service, public _router: Router) {    }

    routerOnActivate(curr: RouteSegment): void {
        let id = curr.getParam('id');
        this._service.getById(id)
            .subscribe(car => {
                this.car = car;
            });
    }
    //some other methods
}

When calling car.getBrands() it gives error: TypeError: self.parent.context.car?.getBrands is not a function

回答1:

I suppose the likely problem is located here:

 this._service.getById(id)
    .subscribe(car => {
      this.car = car; // you just init object like { id: '1', name: 'name'}
    });

Probably your service looks like this:

getById(id: string) {
   return this.http.get('app/car.json')
     .map(data => data.json());     
} 

Try to get Car model from service like this:

getById(id: string) {
   return this.http.get('app/car.json')
     .map(data => data.json())
     .map(car => new Car(car.id, car.name));  <== add this line   
}   

This way car will be instance of Car class and will have appropriate methods like getBrands, addBrand...

Hope it helps!