从服务器

时间:2017-05-10 15:25:09

标签: javascript angular typescript observers

我尝试在google上搜索但找不到解决方案,所以问题就出现了:

我正在尝试使用http模块从角度加载来自服务器的数据,但问题是这里有多个组件需要特定数据,这是我到目前为止所尝试的:

@Injectable()
export class CoreService {
    data: any = null;
    Event: Observable<Object>;     
    isLoadingData: boolean = false;

    constructor(private httpService: HttpService) {
        if(!isNull(this.data)) { return observer.next({data:this.data, isBusy: isLoading}) }  // If Data is not null then return the data 

        if(this.isLoadingBaseDirectory) {
            return observer.next({data:this.isLoadingBaseDirectory, isBusy: this.isLoading}) // if http call is busy loading the data then return isBusy true
        }

        this.isLoading = true; // Data is empty and we are not loading data, then set isLoading flag to true
        this.httpService.get(`coreEnv/getPodiumBaseDirectory`).map((res:Response) => { return res.json() }).subscribe((data) => {
             this.data = data; // data load complete 
             this.isLoading = false;
             observer.next({data:this.data, isBusy: this.isLoading});
        })
    }
}

// Component ngOnInit Method:
this.isBusy = true; // Component Loading Flag
this.coreService.baseDirectoryEvent.subscribe((data) => {
  if(!data['isBusy']) {
    this.data = data['data'];
    this.isBusy = false;
  }
})

现在,如果我在多个组件中使用上面的代码并将它们加载到同一页面中,则第二个组件会从服务中获取响应isBusy标记true,因为第一个组件尝试加载在服务中将isBusy标志设置为true的数据,但是当服务成功从服务器加载数据时,它不会触发第二个组件的最后observer.next,但第一个组件获取数据。

2 个答案:

答案 0 :(得分:1)

正如@GünterZöchbauer在评论中提到的,要实现此功能,请参阅答案:What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?

为我工作!

答案 1 :(得分:0)

您使用的是路由吗?如果是这样,您可以使用解析程序定义无组件父路径。解析器可以获取数据,然后所有孩子都可以访问该数据。

我在这里有一个示例:APM-Final文件夹中的https://github.com/DeborahK/Angular-Routing。查看product-resolver.service.ts。

此父路由的子路径可以使用与此类似的语法访问数据:

ngOnInit(): void {
    this.route.parent.data.subscribe(data => {
        this.product = data['product'];
    });
}

这是在数据属性上使用subscribe,因为在我的示例中,可以使用不同的参数重新检索数据。

相关问题