我需要在一个组件(组件 A)中设置值并在另一个组件(组件 B)中接收值。组件 A 和组件 B 不是父子关系。
我创建了一个共享服务来在两个组件之间共享数据。我能够设置组件 B 的值,但是当我订阅以获取组件 A 中的值时,它没有被触发。
这是我尝试过的:
我在 @NgModule
providers
数组中添加了服务 appmodule.ts
文件,以便它可用于项目中的所有组件。
服务代码:
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;
}
}
组件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");
}
组件 A:在此处获取值(value)
@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);
});
}
当 ComponentA 加载数据为 null
时,调用 ComponentA 中的触发器。但是当从 ComponentB 调用 buttonClick 时,它不会被调用。
更新:
我发现了问题,我应该正确地表达我的问题。 当 ComponentA 和 ComponentB 在同一个页面(URL)中时,代码可以完美运行。
当 2 个组件位于 2 个不同的页面 (URLS) 时,如何在它们之间发送数据。
示例:用户打开有一个按钮的 URL1(渲染组件 A),用户单击按钮并在一个有按钮的新选项卡中重定向到 URL2(渲染组件 B),当用户点击按钮时,我需要将一些数据传递给 ComponentA 并关闭 URL2。我需要检索在 ComponentB 中传递的数据并在 URL1 中使用它。是否可以使用服务?如果不是,我应该遵循哪种方法?
最佳答案
You could effectively use
Subject
along with the router. So, Here is a live solution for your scenario usingRouter
&Subject
.
您的服务将只包含 -
public setValue(value: string): void {
this.valueObs.next(value);
}
public getValue(): Observable < string > {
return this.valueObs;
}
然后,您的 ComponentB
将包含 -
buttonClick() {
this.socialService.setValue("linked successfully");
this.router.navigate(['/a']);
}
并且,您的 ComponentA
的构造函数将包含 -
this.socialService.getValue().subscribe(data => {
this.dataFromB = data;
console.log('Trigger from ComponentB');
console.log(data);
})
关于未触发 Angular 6 数据共享服务订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54742232/