在不相关的组件之间立即共享数据列表RxJS Angular



我通过服务和BehavorSubject共享数据时遇到问题。在应用程序组件中,我有两个组件不相关。当我点击主出口,想要更新服务上的数据列表并更改sider组件模板上的数据时。

**服务**

// behaviorSubject needs an initial value.
private posts: BehaviorSubject<IPost[]> = new BehaviorSubject([]);
private postList: IPost[] = [];
public posts$ = this.posts.asObservable();
constructor(private http: HttpClient) {
this.initializePosts();
}
initializePosts() {
this.http.get('https://jsonplaceholder.typicode.com/todos').subscribe(
(data: any) => {
this.posts.next(data);
},
error => {
}
);
}
addNew(): void {
console.log('add new');
this.http
.get<IPost>('https://jsonplaceholder.typicode.com/todos/1')
.subscribe(res => {
console.log('start');
this.posts.next(this.posts.getValue().concat([res]));
this.postList.push(res);
console.log('after');
console.log(this.posts.getValue().length);
console.log('end');
});
}

**主要组件**

<button (click)="onClick()">BUTTON</button>
data: string[] = [];
constructor(private mySer: MyService) {}
ngOnInit() {}
onClick(): void {
this.mySer.addNew();
}
}

**侧面组件**

{{ posts.length }} - <button (click)="show()">OK</button>
<ul>
<li *ngFor="let value of posts">{{ value.title }}</li>
</ul>
posts: IPost[] = [];
subscription: any;
constructor(private mySr: MyService) {
mySr.posts$.subscribe((data: any) => (this.posts = data));
}
ngOnInit() {}
show(): void {
console.log(this.posts.length);
this.mySr.show();
}

当向BehaviorSubject<添加更多帖子时,我测试了show功能;IPost[]>。但它不在服务中更新,只在订阅中工作。请帮我解释一下。。。非常感谢。

Stackliltz>https://stackblitz.com/edit/angular-ivy-slzwrj?file=src/app/my.service.ts

首先,建议尽量避免在构造函数中订阅,因为一些绑定,如@input绑定,在构造函数中没有初始化和准备好。我总是使用ngOnInit来订阅我的可观察性。但这不是你犯错的原因吗。

在你的服务中,你应该做:

//from
public posts$ = this.posts.asObservable();
//to
getPosts(): Observable<IPost[]> {
return this.posts.asObservable();
}

然后在你的组件中,你可以订阅这个功能:

posts: IPost[] = [];
constructor(private mySr: MyService) {}
ngOnInit() {
this.posts = this.mySr.getPosts().subscribe(posts => posts)
}

我不知道为什么第一个解决方案不起作用,我希望有人能更好地解释原因。

您可以使用Subject尝试以下解决方案。

为您服务:

@Injectable()
export class MessageService {
private readonly _msgUpdated: Subject<any>;
constructor() {
this._msgUpdated = new Subject();
}
get onMsgUpdated(): Observable<any> {
return this._msgUpdated.asObservable();
}  
sendMessage(msg: any) {
this._msgUpdated.next(msg);
}  
}

然后当你从api得到响应时:

this.ApiClient.updateMsg(this.welcomeMsg)
.subscribe((data) => {
console.log(data);
this._msgService.sendMessage(data);          
});

然后,您可以订阅所需组件的ngOnInit((方法中的observable,如下所示:

ngOnInit(): void {        
this._msgService.onMsgUpdated
.pipe(takeUntil(this._unsubscribeAll)) //Optional to unsubscribe on Destroy
.subscribe(msg => {
if (msg != null) {
console.log(`message received : ${msg}`);
}
});
}

最新更新