首页 > 解决方案 > 在不相关的组件之间即时共享数据列表 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

标签: angularrxjs

解决方案


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

在您的服务中:

@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}`);
        }
      });
  }


推荐阅读