【问题标题】:Angular share data between service and two components服务和两个组件之间的角度共享数据
【发布时间】:2019-04-16 13:26:24
【问题描述】:

我需要从 http 获取 Post[],然后将其显示在 post-list 组件上。我可以删除post-list 模板上的一些项目,并通过导航到我使用post-edit 组件的另一条路线来编辑一些项目。 如何在它们之间共享相同的Post[] 数组,以便更改将立即显示在应用程序中?我假设我需要在服务中存储Post[]?从组件编辑/更新它的正确方法是什么? 在这里,我试图通过服务内的tap() 运算符将Post[] 数组保存在服务内

  getAllPosts(): Observable<Post[]> {
    return this.http.get<Post[]>("https://jsonplaceholder.typicode.com/posts");
  }

  getAllUsersPosts(userId: number): Observable<Post[]> {
    return this.getAllPosts().pipe(
      map((posts: Post[]) => posts.filter((p: Post) => p.userId === userId)),
      tap(posts => {
        //storing to service
        this.userPosts = posts;
      })
    );
  }

在执行删除方法后共享更新的Post[] 我试图将存储的数组发送回订阅者,但它没有帮助

  deletePost(id: number): Observable<any> {
    return this.http.delete(`https://jsonplaceholder.typicode.com/posts/${id}`).pipe(
      mapTo(res => {
        const index = this.userPosts.findIndex(p => p.id == id);
        // console.log(index);
        this.userPosts.splice(index, 1);
        return this.userPosts;
      })
    )
  }

实现这一目标的正确方法是什么?

【问题讨论】:

  • 如何在组件中使用getAllUsersPostsdeletePostuserPosts

标签: angular rxjs


【解决方案1】:

在服务中创建一个 Behavior Subject Singleton 变量并使其成为可观察的。 然后通过导入服务从任何组件订阅该 observable,创建一个实例并订阅该 observable 单例。

private publisherVariable= new BehaviorSubject<string>('empty')
castVariable = this.publisherVariable.asObservable()
this.publisherVariable.next(DATA_YOU_WANT_TO_SEND)

【讨论】:

    【解决方案2】:

    userPosts 的持久性将取决于注入的服务范围。

    尝试为服务提供模块范围或根范围

    @module({
      providers:[PostService]
    })
    export class PostModule{}
    

    或者

    @Injectable({
      provideIn:'root'
    })
    export class PostService{}
    

    避免在模块和组件中将 postservice 作为提供者。

    @Componenent({
      providers:[PostService]
    })
    export class PostComponent{}
    

    【讨论】:

      【解决方案3】:

      创建一个模型并将其创建为singleton,在您的服务中使用此singleton,以便传递和更新相同的引用。仅作为示例

      export class PostsModel {
          private static instance: PostsModel;
          public prop1: type = '';
          public prop2: type ='';
          static getInstance() {
              if (!PostsModel.instance) {
                  PostsModel.instance = new PostsModel();
              }
              return PostsModel.instance;
          }
      
          static destroyInstance() {
              delete PostsModel.instance;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-18
        • 1970-01-01
        • 1970-01-01
        • 2018-03-10
        • 1970-01-01
        相关资源
        最近更新 更多