服务可观察不在组件NgOnInIt中工作 - Angular2

问题描述:

我的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://*.com/questions/43055706/how- do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – echonax

你正在登录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

很高兴帮助。 –

当使用Observables时,Observable外部的代码在实际的订阅模块执行之前执行,因为Observables是异步的。来自服务器的响应来自订阅的回调。尝试代码更改为以下:

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