angular - 在不相关的组件之间即时共享数据列表 RxJS Angular
问题描述
我在通过 Service 和 BehavorSubject 共享数据时遇到问题。在应用程序组件中,我有 2 个不相关的组件。当我单击主插座并想要更新服务数据列表并更改侧边组件模板上的数据时。
** 服务 **
// 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<IPost[]> 添加更多帖子时,我使用 show 功能进行了测试。但它不会在服务中更新,仅在订阅中起作用。请帮助我并解释一下......非常感谢。
Stackbliltz > https://stackblitz.com/edit/angular-ivy-slzwrj?file=src/app/my.service.ts
解决方案
您可以使用主题尝试以下解决方案。
在您的服务中:
@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}`);
}
});
}
推荐阅读
- asp.net-core - ASP.NET Core 自定义验证错误消息未本地化
- c++ - kill syscommand 在 Catch2 测试用例中产生失败
- c++ - 数组升序排序嵌套循环问题
- apache-camel - 在 Apache Camel 2.21.5 Olingo4 组件中使用 httpclientBuilder
- angular - Angular 中使用的语法是什么,例如:@NgModule 和 @Component 以及 @Injectable?(使用@符号声明)
- google-apps-script - sheet.isRowHiddenByFilter(n) 不能与切片器一起使用吗?
- php - 是否有任何解决方案可以使用 PHP 在 foreach 中使用不同的变量运行相同的查询?
- python - 如果端口更改,容器化烧瓶应用程序不会加载
- c# - c# GetDirectories 返回意外目录(给出具体示例)
- javascript - 如何查询自定义 HTML 元素?