angular - 服务可观察在组件 NgOnInIt 中不起作用 - Angular2

标签 angular typescript angular2-routing angular2-observables

我的 getHero 服务 observable 没有在 HeroDetail 组件的 NgOnInIt 中被调用。

我能够使用 HTTP 来获取和显示数据表,并在单击该行时路由到详细信息页面。然后我使用 url 的“id”参数来获取 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));
  }
}

hero-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);
  }

}

最佳答案

您正在记录 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);
    });
}

关于angular - 服务可观察在组件 NgOnInIt 中不起作用 - Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43390247/

相关文章:

angular - 来自 Angular 5 中的 json 对象的动态嵌套 Material 菜单

javascript - 使用回调 Angular 5 在异步加载中获取变量

typescript - 函数参数的 this 关键字

Angular2 - 在指令中更改 innerHTML 时动态创建 routerLink

没有导航栏的 Angular 2 路由

带有参数的 Angular 2 路由重新初始化组件 onInit

json - 如何解析 Ionic 上 API 调用的 Json 数据响应,如下所示

angular-ui-router - Angular 2 组件路由

angular - 如何在 typescript 中声明和处理 float 类型?

javascript - 使用 typescript 安装express.js 的正确方法是什么?