2016-04-07 5 views
1

Я только начинаю изучать угловые. У меня проблема при вызове службы в угловом режиме. Служба звонит успешно, но у меня проблема, как я могу обрабатывать данные. В Angular1 мы делаем так:Calling Service в Angular2

DemoService.getExchangeDataConnection().then(function(response){ 
//here we handle all the data 
}) 

Angular2

constructor(private _sampleService: SampleService){ 
    this._sampleService = _sampleService; 
} 


onClickMe(){ 
    this.clickMessage ='You are my hero!'; 
    this.error = ""; 
    this.countries = []; 
    this._sampleService.test() 
    .subscribe(
     data => this.countries = data, 
     error => this.error = "Region " + this.region + " is invalid." 
    ); 

    } 

здесь Как я могу обрабатывать данные Вот моя служба:

export class SampleService { 

constructor(http: Http){ 
     this.http = http; 
    } 

    test(){ 
console.log(AppSettings.API_ENDPOINT); 
    return this.http.get(AppSettings.API_ENDPOINT+"oceania").toPromise() 
     .then(res => console.log(res.json()), err => console.log(err)); 
    } 

} 
+0

Не конвертировать вы HTTP называют пообещать. – Chandermani

ответ

4

Если метод test возвращает наблюдаемым вам нужно подписываться на него аналогичным образом, чем с обещаниями:

this._sampleService.test() 
    .subscribe(
    data => this.countries = data, 
    error => this.error = "Region " + this.region + " is invalid." 
    ); 

Например, для test метода, как это:

test() { 
    return this.http.get('http://...').map(res => res.json()); 
} 

Вы можете заметить, что вы можете также использовать обещание с Angular2. В этом случае вы будете обрабатывать ответ так же, как и вы.

Редактировать

Вы можете обновить ваш метод test таким образом:

test(){ 
    console.log(AppSettings.API_ENDPOINT); 
    return this.http.get(AppSettings.API_ENDPOINT+"oceania") 
       .map(res => console.log(res.json()); 
} 

и назвать его так:

this.service.test().subscribe(data => { 
    (...) 
}); 

Если вы хотите использовать обещание, что вам нужно верните что-то в свой then callback для соединения цепочки:

test(){ 
    console.log(AppSettings.API_ENDPOINT); 
    return this.http.get(AppSettings.API_ENDPOINT+"oceania").toPromise() 
    .then(res => res.json(), err => console.log(err)); // <--------- 
} 

Вы можете получить данные в настоящее время этот путь:

this.service.test().then(data => { 
    (...) 
}); 
+0

Я получил подписку не является функцией – Karan

+0

Что возвращает метод 'test'? –

+0

это возвращает данные, но я не знаю, как я могу обращаться с этим – Karan

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