2017-08-12 119 views
1

在我的角度项目中,我有以下设置:角等待初始加载

我有API的应用程序负载的开头来从服务器的一些数据:

ItemFetch.ts

在应用程序加载开始时,它从API中提取数据,然后将itemLoaded更改为true。

import { Http } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

... 
dataLoaded: boolean = false; 

dataAPI(){ //Stores in local storage 
... 
    .then(data=>{ 
    this.itemLoaded = true; 
    })  
... 
} 

main.ts:

然后,一旦数据被存储,我只需要加载存储数据时itemLoadedItemFetch.ts是真实的。

import { dataFromStorage} from './data_from_storage' //local storage 

export class main_page {   

constructor(public itemStorage: dataFromStorage){}; 

ngOnInit(){ 
    this.fetchInitialData(); 
} 
    //Fetch the data from the storage 
    fetchInitialData(){ 
    this.itemStorage.GetItemDataFromStorage('some_item_id') 
     .then((data) => { 
      console.log("Got the data!" + data); 
    ) 
    }; 

} 

问:

我如何从一个组件共享此dataLoaded到另一个,这样我可以启动this.fetchInitialData();只有当dataLoaded是真的吗?

+1

我会将变量存储在单例服务中。这样,两个组件都可以注入服务并使用它。 – LLai

回答

1

每当你发现自己在想:“我需要代码才能运行,但只有在X发生后”,你基本上需要一个事件处理程序。在Angular中,最简单的方法就是使用RxJS Observables。

有全权负责通知所有感兴趣的听众数据已到达的服务。

export class LoadNotifierService{ 
    public dataLoaded : ReplaySubject<any> = new ReplaySubject(); 
} 

AppModule.providers阵列提供这项服务,并在加载数据的组件注入的服务,并在需要了解的所有组件加载完成。

itemFetch:获取数据,然后引发事件

// .next() will cause the ReplaySubject to emit TRUE 
loadData().then(e => this.loadNotifier.dataLoaded.next(true)); 

主要:注册事件处理通知当数据到达

ngOnInit(){ 
    // Subscribe will receive notice when the ReplaySubject emits 
    // .take(1) guarantees that this will be run only once per ngOnInit() 
    this.loadNotifier.dataLoaded.take(1).subscribe(e => this.fetchInitialData()) 
} 

您可能需要修复几个错误(我没有运行代码),但你得到了我希望的逻辑。

+0

谢谢你的回答。我明白你的答案,非常感谢。只是一个简单的问题。 'ReplaySubject = new ReplaySubject();''做?谢谢! –

+1

它将'dataLoaded'定义为'ReplaySubject'类型。它是一个对象,通过'ReplaySubject.next()'可以很容易地通知监听器何时发生重大事件。它还可以轻松地使用'ReplaySubject.subscribe()'' – BeetleJuice

+0

来收听这些通知。谢谢!非常感激! =) –