【问题标题】:Angular 2 injectable async executionAngular 2 可注入异步执行
【发布时间】:2016-11-24 07:49:36
【问题描述】:

我正在使用 Angular 和 RxJS 编写项目。我实现了从 JSON 中检索数据的可注入类,如下所示:

import {Injectable, Inject} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

import {Student} from './student.data';

@Injectable()
export class RosterService {
    private students : Student[];
    constructor(@Inject(Http) private http:Http){}

    private getStudents(){
        this.http.get('/JSON/students.json')
            .map(data => data.json().students)
            .subscribe(data => this.students = data);
    }

    public getRoster() {
        this.getStudents();
        return this.students;
    }
}

在我将 RosterService 注入 AppComponent 的构造函数后(包括作为提供者的 @Component):

export class AppComponent {
    public students : Student[];
    constructor(private _rosterService : RosterService) {
        this.students = _rosterService.getRoster();
    }
 }

但是当我调用 getRoaster() 方法时,它不会等到 getStudents (async get call) 被执行。结果我得到未定义的值。

我该如何处理?谢谢回复。

【问题讨论】:

    标签: typescript angular rxjs


    【解决方案1】:

    你应该像这样返回Observable<Student[]> from thegetRoster`方法

    getRoster(): Observable<Student[]>{
           return this.http.get('/JSON/students.json')
                .map(data => data.json().students);
        }
    

    然后在app component订阅结果

    export class AppComponent {
        public students : Student[];
        constructor(private _rosterService : RosterService) {
           _rosterService.getRoster().subscribe(students => this.students = students);
        }
     }
    

    另外,最好通过实现OnInit接口来调用ngOnInit中的服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多