2015-12-24 2 views
1

В моем проекте Angular 2 ListService не может получить данные с сервера через сообщение. Я получаю эту ошибку:TypeError: Невозможно прочитать свойство 'post' of undeined in [null]

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 <anonymous> (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:10897:14), <anonymous>: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) 

Моего ListingService.ts выглядит следующим образом:

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<Listing>; 
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<Listing>) => 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]); 
} 
} 

И в ListingsComponent, который использует ListingService, выглядит следующим образом:

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

Что может быть проблемой этого?

ответ

3

Вы должны добавить HTTP_PROVIDERS либо массив компонент providers как это:

providers: [HTTP_PROVIDERS] 

или предпочтительно в загрузчике, как это:

bootstrap(AppComponent, [HTTP_PROVIDERS]); 

И вам не хватает инъекции constructor HTTP в ListingService

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

добавление

Причина вы не получаете никаких списков, потому что вы используете обещание вместо Observable:

в getListings() в ListingService возвращения этого:

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

затем подписаться на этот в getListings() в ListingsComponent:

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

Я добавил HTTP_PROVIDERS для начальной загрузки. Я добавил конструктор в ListService, как вы писали, ошибки исчезли. Но данные (листинга) пока не показаны (( –

+0

Это совершенно другая проблема. Вы используете обещания вместо наблюдаемых/подписчиков, которые имеют угловое значение. Я предлагаю вам создать другой вопрос. Но чтобы дать вам несколько указателей, плохо сделайте маленькое добавление к моему сообщению – PierreDuc

+1

ВАМ ЯВЛЯЕТСЯ ГЕНИЙ! Спасибо большое! –

0

Вы должны вернуть наблюдаемый объект из вашего запроса в службе:

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

И подписываться слушателем от компонента:

export class CompanyList implements OnInit { 
    public companies: Company[]; 

    constructor(private service: CompanyService) { 
    this.service = service; 
    } 

    ngOnInit() { 
    this.service.getCompanies().subscribe(
     data => this.companies = data); 
    } 
} 

Надеется, что это помогает вам, Тьерри

Смежные вопросы