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

前端 未结 2 1152
野性不改
野性不改 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);
    }
    
    0 讨论(0)
  • 2020-12-21 19:35

    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

    0 讨论(0)
提交回复
热议问题