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

Angular Service Listen when data is Loaded from Server

我已经尝试在 google 上搜索但找不到解决方案,所以问题出在这里:

我正在尝试使用 angular 中的 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 但第一个组件获取数据。

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

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

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

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

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

正如@Günter Zöchbauer 在他的评论中提到的那样,要实现此功能,请参阅答案:

对我有用!