How to send data from one component to another using a shared service [duplicate]

好久不见. 提交于 2019-11-29 14:26:51

By putting:

@Component({
  .....
  providers: [sharedService]
})

in both components, you are creating two distinct instances of the shared service. Each instance is not 'aware' of the data from each component. Provide it at module level and create a singleton service:

@NgModule({
  ....
  providers: [sharedService]
})

This way, you inject the service as a single instance in the both components, so they can share it as they will share the data.

Or using the Angular's preferred new way :

Beginning with Angular 6.0, the preferred way to create a singleton service is to specify on the service that it should be provided in the application root. This is done by setting providedIn to root on the service's @Injectable decorator:

@Injectable({
  providedIn: 'root',
})

Demo

See also

I dont know why sub$ is used but you dont need that

// just push data to subject. you can use BehavourSubject to initiatte a value.
@Injectable()
export class shareService{

  private sub = new Subject();

    confirmMission(astronaut: string) {
    this.sub.next(astronaut);
  }

}

And then in your 2nd component sub scribe it

@Component({
  selector: 'hello',
  template: `<h1>Hello!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
  providers:[shareService]  // this can be shared in module lebel or componenet level
})
export class HelloComponent  {
  subscription: Subscription;
    constructor(private share : shareService){
    this.subscription =  share.subj.subscribe(val=>{
    console.log(val);
    })
  }
} 

make sure to provide your service in module level or provide it in both the component.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!