好吧,所以我知道这已被多次询问了 - 我已经阅读了许多答案和文档,但无论出于什么原因,这都不是飞行。我想至少证实我没有错过任何东西。
两个组件,一个服务,两个组件都需要与服务进行交互,其中一个组件需要在服务成员发生更改时做出反应。
使用包含域对象的BehaviorObject获得服务
putIntoField(city: string) {
this.searchText = city;
console.log(city);
}
让一个组件侦听Service的BehaviorObject
上的更改@Injectable()
export class MyService {
addedMyObject:Subject<MyObject> = new BehaviorSubject();
constructor(private http:Http) {}
getAndAddMyObject(objectId:string) {
this.getMyObject(objectId) // pretend this method exists
.subscribe((o) => {
this.addedMyObject.next(w);
});
}
}
让第二个组件调用服务进行更改
export class MyFirstComponent() implements OnInit {
constructor(private myService : MyService) {}
ngOnInit() : void {
this.myService.addedMyObject
.subscribe((o) => {
console.log("Incoming object, add to a list or something");
})
}
}
不知何故,MyFirstComponent的订阅没有解雇。这有点让我疯狂。什么是黑客?
答案 0 :(得分:0)
你的代码中有很多打字错误,所以我无法真正告诉你要解决什么,但我在本地尝试了它并且它有效:
<强>服务强>
@Injectable()
export class MyService {
addedMyObject = new BehaviorSubject<any>(null);
getAndAddMyObject(objectId: string) {
this.getMyObject(objectId).subscribe(o => {
this.addedMyObject.next(o);
});
}
getMyObject(id: string): Observable<any> {
return Observable.of({key: 'value'});
}
}
组件1:
@Component({
selector: 'first',
template: `
Hi
`,
})
export class MyFirstComponent implements OnInit {
constructor(private myService: MyService) {}
ngOnInit(): void {
this.myService.addedMyObject.subscribe(o => {
console.log("Incoming object, add to a list or something", o);
})
}
}
组件2:
@Component({
selector: 'second',
template: `
<button (click)="addSelectedObjectToSomething(1)">Add</button>
`,
})
export class MySecondComponent {
constructor(private myService: MyService) {}
addSelectedObjectToSomething(objectId) {
this.myService.getAndAddMyObject(objectId);
}
}
当我点击第二个组件的按钮时,我会看到显示正确对象的日志。