angular 2 - Share Service On Load

后端 未结 2 2026
忘了有多久
忘了有多久 2021-01-26 12:13

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 cla         


        
相关标签:
2条回答
  • 2021-01-26 12:32

    I can suggest a work around for the ExpressionChangedAfterItHasBeenCheckedError.

    This is a genuine error as pointed out by gunter here https://stackoverflow.com/a/43375600/2708210

    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)); 
    

    This is a peice of code from my app git link

    0 讨论(0)
  • 2021-01-26 12:43

    Subject will emit value its subscription when they are subscribe to it. When you're pushing value inside you CommonList from ngOnInit, it does emit value. But the underlying inner component(event subscription) haven't happened yet.

    You could fix this issue just by using ngAfterViewInit lifecycle hook, where it ensures that inner Component tree have been initialize(expect content projection). Essentially it will ensure that component subscription have been happened.

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

    Or another way of achieving the same goal would be, use BehaviourSubject inspite of Subject. There difference between these two is BehaviourSubject store & emits its last subscription.

    0 讨论(0)
提交回复
热议问题