本文介绍了angular 2-负载共享服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将服务共享给组件,为此,我创建了service.ts,其代码如下所示:

I am trying to share service to a component, for this, I have created service.ts where the code looks like:

import { Subject } from 'rxjs/Subject';

export class CommonService {
    CommonList = new Subject<any>();
}

当然,此服务在app.module.ts的提供程序列表中然后,我有一个组件边栏.我正在侧边栏组件中订阅此服务:

Of course, this service is in provider list in app.module.tsThen, I have a component sidebar.From sidebar component i am subscribing this service:

  ngOnInit() {
    this.subscription = this.CommonServicePrivate.CommonList.subscribe(
      (result: any) => {
        console.log(result);
      }
    );
  }

这是问题所在,如果我尝试通过某种方法从app.component.ts在此服务中添加一些列表:

Here is the problem, If I try to add some list in this service from app.component.ts via some method:

  click(){
   this.CommonService.CommonList.next([{"some_key":"some_value"}]);
  }

这实际上有效,但是当我尝试这样做时:

This actually works, but when i try this:

  ngOnInit(){
    this.CommonService.CommonList.next([{"some_key":"some_value"}]);
  }

它不起作用.

关键是我想将此服务传递给负载应用程序上的组件.

The point is that I want to pass this service to a component on load application.

在ngAfterViewInit的情况下,当我尝试将此结果呈现到某些模板时,出现错误: ExpressionChangedAfterItHasBeenCheckedError:检查表达式后,表达式已更改.上一个值:未定义".当前值:

In case of ngAfterViewInit, when i am trying to render this result to some template, i am getting error:ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value:

如果有人有这种经验,请与我分享.谢谢.

If someone has this experience could you please share to me.Thanks.

推荐答案

我可以建议ExpressionChangedAfterItHasBeenCheckedError的解决方法.

I can suggest a work around for the ExpressionChangedAfterItHasBeenCheckedError.

这是枪手在这里 https://stackoverflow.com/a/43375600/2708210

您可以做的是在setTimeout内进行呼叫,这是我遇到的问题,并且可以解决此问题.

what you can do is make the call inside of a setTimeout i had this issue and this was a work around.

 this.subscription = this.service.spinner$
  .subscribe(item => setTimeout(() => this.showProgress = item, 0));

这篇关于angular 2-负载共享服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:37