如何使用 service 和 observable 在组件之间共享数据? [英] How to share data between components using service and observable?

查看:24
本文介绍了如何使用 service 和 observable 在组件之间共享数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angular 2+ 的新手,我正在尝试在两个组件之间共享数据,但第二个组件没有从服务中检索数据,而是获取了一个空对象.

Hi I am new to angular 2+, I am trying to share data between two components but the second component is not retrieving the data from the service, it gets an empty object.

Service - 使用 rxjs BehaviorSubject 来保持对象

Service - using rxjs BehaviorSubject to keep the object

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class PostsService {

  response: any = {};
  private messageResponse = new BehaviorSubject(this.response);
  currentResponse = this.messageResponse.asObservable();

  constructor(private http: Http) { }

  // Get all posts from the API
  getAllPosts() {
    return this.http.get('/api/posts')
      .map(res => {
         this.messageResponse.next(res.json());
         return res.json();
      }).catch(err => {
         console.log('caught exception' + err.status);
         return Observable.throw(err);
      });
  }
}

组件 1 - 帖子.该组件第一次调用获取数据,检索没有问题,更新messageResponse.

Component 1 - Posts. This component makes the first call to get the data, and is retrieved no problem, and updates the messageResponse.

export class PostsComponent implements OnInit {
  // instantiate posts to an empty array
  posts: any = [];

  constructor(private postsService: PostsService) { }

  ngOnInit() {
    // Retrieve posts from the API
    this.postsService.getAllPosts().subscribe(posts => {
      this.posts = posts;
    });
  }
}

组件 2 - 帖子 2 - 此组件获取 currentResponse 但日志显示一个空数组.

Component 2 - Posts 2 - This component gets the currentResponse however the log is showing an empty array.

export class Posts2Component implements OnInit {
  posts: any = [];

  constructor(private postsService: PostsService) { }

  ngOnInit() {
    this.postsService.currentResponse.subscribe(posts => {
      this.posts = posts;
      console.log(this.posts);
    });
  }
}

每当我查看 Posts2 组件时,我都看不到任何 currentResponse 数据.我不确定我在这里做错了什么?

Whenever I view the Posts2 component I do not see any of the currentResponse data. I'm not sure what I have done wrong here?

谢谢

推荐答案

User3511041,只有订阅了一个 Observable,该 observable 才会被执行.在一个服务中,我们可以使用三种方法.(我使用 httpClient,而不是旧的"和不推荐使用的"http)

User3511041, only if you subscribe to a Observable, the observable is executed. In a service we can use three approaches. (I use httpClient, not the "old" and "deprecated" http)

@Injectable()
export class PostsService {

  response: any = {};
  private messageResponse = new BehaviorSubject(this.response);
  currentResponse = this.messageResponse.asObservable();

  constructor(private httpClient: Http) { }

  // 1.-Return and observable 
  getAllPosts():Observable<any> {  //see that using httpClient we needn't json()
    return this.http.get('/api/posts').catch(err => {
         console.log('caught exception' + err.status);
         return Observable.throw(err);
      });

  // 2.- using next or  3.-fill an variable
  fillAllPosts():void {  
    this.http.get('/api/posts').catch(err => {
         console.log('caught exception' + err.status);
    }).subscribe(res=>{
          this.messsageResponse.next(res);  //<--(the 2nd approach)
          this.post=res;  //<--or using a variable (for the 3re approach)
    })
}

在组件中,您可以订阅 getAllPost() 或当前响应

In a component you can subscribe to a getAllPost() or to current Response

ngOnInit() {

    //1.-Subscribe to a currentResponse
    this.postsService.currentResponse.subscribe(posts => {
      this.posts = posts;
      console.log(this.posts);
    });
    // in this case we must call to fillAllPost after subscription
    this.postService.fillAllPost();

    //2.-Subscribe to a getAllPost()
    this.postsService.getAllPost().subscribe(posts => {
      this.posts = posts;
      console.log(this.posts);
    });
  }

3re 方法是使用 getter

the 3re approach is using a getter

  //a 3re approach is using a getter
  get post()
  { 
       return this.postService.post;
  }
  ngOnInit() {
       this.postService.fillAllPost()
  }

这篇关于如何使用 service 和 observable 在组件之间共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆