Angular 6数据共享服务订阅未触发

Ani*_*udh 6 singleton callback typescript angular-components angular

我需要在一个组件(组件A)中设置值并在另一个组件(组件B)中接收值.组件A和组件B不是父级和子级.

我创建了一个共享服务来共享两个组件之间的数据.我能够从组件B设置值,但是当我订阅以获取组件A中的值时,它不会被触发.

这是我尝试过的:

@NgModule providersappmodule.ts文件中添加了Service in array,以便它可用于项目中的所有组件.

服务代码:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from '../../node_modules/rxjs';

@Injectable({
  providedIn: 'root'
})
export class SocialService {

  constructor() { }

  private valueObs: BehaviorSubject<string> = new BehaviorSubject<string>(null);

 public setValue(value: string):void {
     this.valueObs.next(value);
     this.getValue();
 }

 public getValue():Observable<string> {
     return this.valueObs;

 }

}
Run Code Online (Sandbox Code Playgroud)

组件B:此处设置值

@Component({
  selector: 'app-componentb',
  templateUrl: './componentb.component.html',
  styleUrls: ['./componentb.component.scss']
})


constructor(private socialService: SocialService, private http: HttpClient) {



}

 buttonClick()
 {

    this.socialService.setValue("linked successfully");
 }
Run Code Online (Sandbox Code Playgroud)

组件A:在这里获得价值

@Component({
  selector: 'app-componenta',
  templateUrl: './componenta.component.html',
  styleUrls: ['./componenta.component.scss']
})


constructor(private socialService: SocialService, private http: HttpClient) {

       this.socialService.getValue().subscribe(data=>{

    console.log('Trigger from ComponentB');
    console.log(data);

});

}
Run Code Online (Sandbox Code Playgroud)

当ComponentA加载数据时,正在调用ComponentA中的触发器null.但是当从ComponentB调用buttonClick时,它不会被调用.

更新:

我想出了问题,我应该正确地表达我的问题.当ComponentA和ComponentB位于同一页面(URL)中时,代码完美无缺.

如何在2个不同页面(URLS)中的2个组件之间发送数据.

示例:用户打开URL1(呈现ComponentA),其中有一个按钮,用户点击按钮并在一个带有按钮的新选项卡中重定向到URL2(渲染ComponentB),当用户点击按钮时,我需要传递一些数据到ComponentA并关闭URL2.我需要检索ComponentB中传递的数据并在URL1中使用它.是否可以使用服务?如果没有,我应该遵循哪种方法?

Tus*_*ade 8

您可以有效地Subject与路由器一起使用。因此,是使用Router&的场景的实时解决方案Subject

您的服务将简单地包含 -

public setValue(value: string): void {
    this.valueObs.next(value);
}

public getValue(): Observable < string > {
    return this.valueObs;
}
Run Code Online (Sandbox Code Playgroud)

那么,你的ComponentB遗嘱包含——

buttonClick() {
    this.socialService.setValue("linked successfully");
    this.router.navigate(['/a']);
}
Run Code Online (Sandbox Code Playgroud)

而且,您ComponentA的构造函数将包含 -

this.socialService.getValue().subscribe(data => {
    this.dataFromB = data;
    console.log('Trigger from ComponentB');
    console.log(data);
})
Run Code Online (Sandbox Code Playgroud)