Angular 2的可观察对象.直到第二次调用Subscribe时才执行



我试图让这个组件从返回一个可观察对象的服务中获得字符串数据

import { Component, OnInit, OnDestroy } from '@angular/core';
import { TabFourService } from "./tabfour.service";
import { Subscription } from "rxjs";
@Component({
    selector: 'tab-four',
    template: `
                {{title}}
              `
})
export class TabFourComponent implements OnInit, OnDestroy{
    title: string = "This is Tab four";
    subscription: Subscription;
    constructor(private tabfourService: TabFourService){}
    ngOnInit(){
        console.log("now in init");
        this.getItems();
        this.getItems();
    }
    getItems(){
        console.log("now in get items");
        this.subscription = this.tabfourService.getItems()
                                .subscribe(data => console.log("testing observable"));
    }
    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

这是一个简单的服务:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
import { Observable } from "rxjs";
@Injectable()
export class TabFourService {
    items: string;
    private itemSource = new Subject<string>();
    constructor(){}
    itemSource$ = this.itemSource.asObservable();
    getItems(): Observable<string> {
        this.itemSource.next("aaa");
        return this.itemSource$;
    }
}

我在@NgModule()中将该服务列为提供商,这样它就可以被所有组件实例共享。TabFourComponent还有一个路由器,所以每次我导航到它时,我都应该在控制台中看到"测试可观察对象"。但是直到两次调用getItems()才显示出来。我想知道为什么它没有在第一次被触发。

tabfour.component.ts:20  now in init
tabfour.component.ts:26  now in get items
tabfour.component.ts:26  now in get items
tabfour.component.ts:28  testing observable
编辑:

而在另一种情况下,服务从http.get

提供数据
// in service
getLibraryFromDatabase(): Observable<any[]> {
  return this.http.get(<some url>)
             .map(data => data.json())
             .catch(this.handleError);
}

组件在订阅后不需要再次调用service的方法。

// in component
ngOnInit() {
    this.subscription = this.libraryService.getLibraryFromDatabase()
                        .subscribe(libs => this.createLibs(libs));
}

如果直到第二次getItems()执行时才调用订阅的方法,这是因为在订阅接管之前触发了事件。在ngOnInit方法中注册订阅(这是做这类事情的最佳位置),然后调用触发您订阅的事件的方法:

ngOnInit() {
    this.subscription = this.tabfourService.getItems()
                            .subscribe(data => console.log("testing observable"));
    // The subscription has been taken in charge, now call the service's method
    this.tabFourService.getItems();
}

最新更新