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

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

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 undefined in [null] ORIGINAL EXCEPTION: TypeError: Cannot read property 'post' of undefined ORIGINAL STACKTRACE: TypeError: Cannot read property 'post' of undefined at ListingService.getListings (http://localhost:3000/app/listing.service.js:30:30) at ListingsComponent.getListings (http://localhost:3000/app/listings.component.js:45:41) at ListingsComponent.ngOnInit (http://localhost:3000/app/listings.component.js:41:26) at AbstractChangeDetector.ChangeDetector_HostListingsComponent_0.detectChangesInRecordsInternal (eval at  (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:10897:14), :22:99) at AbstractChangeDetector.detectChangesInRecords (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8824:14) at AbstractChangeDetector.runDetectChanges (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8807:12) at AbstractChangeDetector._detectChangesContentChildren (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8871:14) at AbstractChangeDetector.runDetectChanges (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8808:12) at AbstractChangeDetector._detectChangesInViewChildren (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8877:14) at AbstractChangeDetector.runDetectChanges (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8811:12)

My ListingService.ts looks like this:

import {Injectable, Injector} from 'angular2/core'; import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http'; import {Listing} from './listing'; import 'rxjs/add/operator/map'; @Injectable() export class ListingService {  http: Http;  listings: Array;  getListings() {     var headers = new Headers();     headers.append('Content-Type', 'application/json');     this.http.post('http://144.376.29.134:and-so-on', JSON.stringify(     {"id":1, "title": "Title", "description": "Проводите", "discount": "21%", "imageUrl": "http://lorempixel.com/400/200/sports", "tags": [{"tag": "Еда"}]     }),{headers:headers}     ).map(res => res.json())     .subscribe((res:Array) => this.listings = res);     return Promise.resolve(this.listings);  }  getListing(id: number) {     return Promise.resolve(this.listings)     .then(listings => listings.filter(l => l.id === id)[0]);  } }

And the ListingsComponent, which uses ListingService, looks like this:

import {Component, OnInit} from 'angular2/core'; import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http'; import {Listing} from './listing'; import {ListingService} from './listing.service'; import 'rxjs/add/operator/map'; @Component({   .... }) export class ListingsComponent implements OnInit {  listings: Array;  constructor(private listingService:ListingService, private _router: Router) {}  ngOnInit() {   this.getListings();  }  getListings() {   this.listingService.getListings().then(listings => this.listings = listings);  }  getListing(id: number) {   return Promise.resolve(this.listings)   .then(listings => listings.filter(l => l.id === id)[0]);  }  gotoDetail(listing: Listing) {   this._router.navigate(['ListingDetail', { id: listing.id }]);  } }

What can be problem of this?

回答1:

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); }


回答2:

You should return the observable object from your request in the service:

@Injectable() export class CompanyService {   constructor(http:Http/*, routeParams: RouteParams*/) {     this.http = http;   }    getCompanies() {     return this.http.get('https://angular2.apispark.net/v1/companies/')             .map(res => res.json());   } }

And subscribe a listener from your component:

export class CompanyList implements OnInit {   public companies: Company[];    constructor(private service: CompanyService) {     this.service = service;   }    ngOnInit() {     this.service.getCompanies().subscribe(       data => this.companies = data);   } }

Hope it helps you, Thierry



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!