3

我的getHero服務可觀察未在HeroDetail組件中的NgOnInIt中調用。服務可觀察不在組件NgOnInIt中工作 - Angular2

我可以使用HTTP獲取&顯示數據表&路由到單擊該行時的詳細信息頁面。然後,我使用url的「id」參數來獲取id,但同樣不能使用getHero函數來獲取特定的行詳細信息。

身份證顯示在控制檯中,但英雄來了未定義。我嘗試了很多東西,但目前爲止還沒有工作。任何幫助將不勝感激。

以下是我的代碼供參考。

hero.service.ts

import { Injectable }    from '@angular/core'; 
import { Http, Response }   from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/map'; 
import { Hero } from './hero'; 

@Injectable() 
export class HeroService { 
heroes: Hero[]; 
hero: Hero; 

    private heroesUrl = 'SERVICE URL'; 
    constructor (private http: Http) {} 

    getHeroes(): Observable<Hero[]> { 
    return this.http.get(this.heroesUrl) 
        .map(this.extractData) 
        .catch(this.handleError); 
    } 
    private extractData(res: Response) { 
    let body = res.json()['data']; 
    console.log(body); 
    return body || { }; 
    } 
    private handleError (error: Response | any) { 
    // In a real world app, you might use a remote logging infrastructure 
    let errMsg: string; 
    if (error instanceof Response) { 
     const body = error.json() || ''; 
     const err = body.error || JSON.stringify(body); 
     errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
    } else { 
     errMsg = error.message ? error.message : error.toString(); 
    } 
    console.error(errMsg); 
    return Observable.throw(errMsg); 
    } 

getHero(id: number): Observable<Hero> { 
    return this.getHeroes() 
     .map(heroes => heroes.find(hero => hero.cc_id == id)); 
    } 
} 

英雄detail.component.ts

import { Component } from '@angular/core'; 
import { Router, ActivatedRoute, Params } from '@angular/router'; 
import { HeroService } from './hero.service'; 
import { Hero } from './hero'; 

@Component({ 
    template: ` 
    <h2>INNER PAGE {{ this.id }}</h2> 
    `, 
    providers: [HeroService] 
}) 

export class HeroDetailComponent { 

errorMessage: string; 
    hero: Hero; 
    heroes: Hero[]; 
    id: number; 
    mode = 'Observable'; 

    constructor (
    private service: HeroService, 
    private route: ActivatedRoute, 
    private router: Router 
) {} 


ngOnInit() { this.getHeroes() } 

    getHeroes() { 
    this.id = this.route.snapshot.params['id']; 
    console.log(this.id); 

    this.service.getHero(this.id).subscribe(hero => this.hero = hero); 
    console.log(this.hero); 
    } 

} 
+6

的可能的複製[?我如何返回從angular2可觀察/ HTTP /異步調用的響應(http://stackoverflow.com/questions/43055706/how- do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – echonax

回答

1

你正在登錄this.hero調用完成之前。這是因爲Http調用是異步完成的。

getHeroes() { 
    this.id = this.route.snapshot.params['id']; 
    console.log(this.id); 

    this.service.getHero(this.id).subscribe(hero => { 
     this.hero = hero; 
     console.log(this.hero); 
    }); 
} 
+0

謝謝@Mario。這工作! – Jamshed

+0

很高興幫助。 –

0

當使用Observables時,Observable外部的代碼在實際的訂閱模塊執行之前執行,因爲Observables是異步的。來自服務器的響應來自訂閱的回調。嘗試代碼更改爲以下:

this.service.getHero(this.id).subscribe(hero => { 
    this.hero = hero; // assign the class variable values here 
    console.log(this.hero); 
    }); 
}