我正在尝试与Subject在Angular 6中的两个组件之间共享数据。 不知何故,它不起作用,我找不到原因。我需要单击将数据从compare.component传递到profile.component。当我单击时,不会传递数据。但是以某种方式,当我返回并再次单击时,它可以工作。 我该怎么办?
data.service
import {Subject} from 'rxjs';
export class DataService {
data = new Subject();
}
profile.component
export class ProfileComponent implements OnInit {
constructor(private dataService: DataService, private router: Router) { }
ngOnInit() {
}
sendData(x) {
this.dataService.data.next(x);
this.router.navigate(['compare']);
}
}
compare.component
export class CompareComponent implements OnInit {
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.data.subscribe(
(data) => {
console.log(data);
}
);
}
}
答案 0 :(得分:0)
在使用中:
export class DataService {
private data = new Subject<any>();
public data$ = this.data.asObservable();
emitdata(x: any){
this.data.next(x);
}
}
在个人资料组件中:
sendData(x){
this.dataservice.emitdata(x);
}
在比较组件中:
ngOnInit() {
this.dataService.data$.subscribe(
(data) => {
console.log(data);
}
);
}
答案 1 :(得分:0)
使用BehaviorSubject它将订阅最新值
import {BehaviorSubject} from 'rxjs';
export class DataService {
//You can set initial value as well if you want new BehaviorSubject('value');
data = new BehaviorSubject();
}