TypeError: Cannot read property 'post' of undefined in [null]

前端 未结 2 1153
野性不改
野性不改 2020-12-21 19:23

In my Angular 2 project ListingService can\'t get data from server via post. I\'m getting this error:

EXCEPTION: TypeError: Cannot read property \'post\' of          


        
2条回答
  •  自闭症患者
    2020-12-21 19:33

    You have to add HTTP_PROVIDERS to either the component providers array like this:

    providers: [HTTP_PROVIDERS]
    

    or preferably in the bootstrap like this:

    bootstrap(AppComponent, [HTTP_PROVIDERS]);
    

    And you are missing the constructor http injection in the ListingService:

    export class ListingService {
       constructor(private http : Http){}
    }
    

    addendum

    The reason you are not receiving any listings is because you are using a Promise instead of Observable:

    in getListings() in ListingService return this:

    return this.http.post("bla bla").map(res => res.json).map((res) => {
        return this.listings = res;
    });
    

    then subscribe to this in the getListings() in the ListingsComponent:

    getListings() {
      this.listingService.getListings().subscribe(listings => this.listings = listings);
    }
    

提交回复
热议问题