3

私のgetHeroサービスのobservableがHeroDetailコンポーネントのNgOnInItで呼び出されていません。サービスオブザーバブルがコンポーネントNgOnInItで動作しない - Angular2

HTTPを使用して&のデータテーブルを表示すると、&の行がクリックされたときに詳細ページにルーティングされます。次に、idを取得するためにURLの「id」パラメータを使用していますが、特定の行の詳細を取得するためにgetHero関数を使用していません。

IDはコンソールに表示されますが、英雄は定義されていません。私はたくさんのものを試しましたが、これまでに何も働いていませんでした。どんな助けも高く評価されます。

以下は参考用です。

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-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

観測を使用する場合、実際に観測が非同期であるため、ブロックの実行加入前、観測外部コードが実行されます。サーバーからの応答は、サブスクリプションのコールバックにあります。以下にコードを変更してみてください:

this.service.getHero(this.id).subscribe(hero => { 
    this.hero = hero; // assign the class variable values here 
    console.log(this.hero); 
    }); 
} 
関連する問題