如何使用service和observable在组件之间共享数据?

时间:2018-04-28 11:48:40

标签: angular rxjs observable angular-services behaviorsubject

嗨,我是角度2+的新手, 我试图在两个组件之间共享数据,但第二个组件没有从服务中检索数据,它得到一个空对象。

服务 - 使用rxjs BehaviorSubject保留对象

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。

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,但日志显示为空数组。

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数据。我不确定我在这里做错了什么?

由于

1 个答案:

答案 0 :(得分:3)

User3511041,仅当您订阅Observable时,才会执行observable。 在服务中,我们可以使用三种方法。 (我使用httpClient,而不是"旧"和#34;弃用" 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()或当前响应

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

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