javascript - 从服务器加载数据时,Angular 服务监听

标签 javascript angular typescript observers

我尝试在谷歌上搜索但找不到解决方案,所以问题是:

我正在尝试使用 http 从服务器加载数据 Angular 模块,但问题是多个组件需要特定数据,这是我迄今为止尝试过的:

@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对于第二个组件,但第一个组件获取数据。

最佳答案

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

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

作为该父路由的子路由的任何路由都可以使用类似于以下的语法访问数据:

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

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

关于javascript - 从服务器加载数据时,Angular 服务监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43896778/

相关文章:

javascript - 尝试使用 js 附加到元素?

javascript - 如何将 html 元素列表作为参数传递到 Closure 模板中

angular - 如何使用 angualr2 和 typescript 将图像上传到 azure 存储 blob

javascript - 在 AngularJS 和非 AngularJS 弹出窗口之间共享变量

html - Angular Material 努力调整对话框元素的宽度

html - 如何覆盖 angular2 中 md-input-container 的样式?

angular - 如何在 Typescript 中初始化类型化数组

javascript - RxJS:如何等待多个可观察对象,即使一个或多个失败

typescript - Angular2 访问全局服务而不将其包含在每个构造函数中

javascript - 如何从匿名鼠标事件函数内部访问变量?