首页 > 解决方案 > 订阅 Observable 与订阅 Subject

问题描述

在 Angular 应用程序中有不同的方法可以从服务器获取数据:

  1. 从服务中获取 Observable 并在组件中订阅它
  2. 在服务创建主题并在组件订阅主题

这两种方法都对我有用,但我不明白应该使用哪种方法。

第一种方法从服务中获取 Observable 并在 component 订阅它

文章.service.ts

import { Injectable } from '@angular/core';
import { Article } from '../models/article';
import { AngularFirestore } from '@angular/fire/firestore';
import { map, take } from 'rxjs/operators';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: "root"
})
export class ArticleService {
  public articlesChanged: Subject<Article[]> = new Subject<Article[]>();
  articles: Article[];

  constructor(private db: AngularFirestore) {}

  get() {
    return this.db.collection('articles').valueChanges({ idField: 'id' });
  }
}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { ArticleService } from 'src/app/services/article.service';
import { Observable, Subscription } from 'rxjs';
import { Article } from 'src/app/models/article';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})

export class HomeComponent implements OnInit {
  articles: Article[];

  constructor(private articlesService: ArticleService) { }

  ngOnInit() {
    this.articlesService.get().subscribe(articles => this.articles = articles as Article[]);
  }
}

第二种方法。 在服务上创建主题并在组件上订阅主题:

文章.service.ts

import { Injectable } from '@angular/core';
import { Article } from '../models/article';
import { AngularFirestore } from '@angular/fire/firestore';
import { map, take } from 'rxjs/operators';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: "root"
})
export class ArticleService {
  public articlesChanged: Subject<Article[]> = new Subject<Article[]>();
  articles: Article[];

  constructor(private db: AngularFirestore) {}

  get(): void {
    this.db
      .collection('articles')
      .valueChanges({ idField: 'id' }).subscribe(articles => {
        this.articles = articles as Article[];
        this.articlesChanged.next(this.articles);
      });
  }
}

home.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ArticleService } from 'src/app/services/article.service';
import { Observable, Subscription } from 'rxjs';
import { Article } from 'src/app/models/article';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})

export class HomeComponent implements OnInit, OnDestroy {
  articlesSubscription: Subscription;
  articles: Article[];

  constructor(private articlesService: ArticleService) { }

  ngOnInit() {
    this.articlesSubscription = this.articlesService.articlesChanged.subscribe(articles => this.articles = articles);
    this.articlesService.get();
  }

  ngOnDestroy(): void {
    this.articlesSubscription.unsubscribe();
  }
}

有我应该使用的最佳实践吗?

标签: angularfirebaseangular2-services

解决方案


我们可以说SubjectObservable的一种特殊类型。

Observable:订阅它以获取值。

主题:相同,但您也可以控制要发送到其中的值(可以订阅但也可以发送),您将获得默认值。

为了理解 Subject 和 Observable 之间的区别,您需要了解两个不同的概念

  • 数据生产者
  • 数据消费者

根据定义,可观察对象是数据生产者。也就是说,一种可以随时间产生数据的特殊类型。

另一方面,Subject 既可以充当数据生产者,也可以充当数据消费者

这意味着两件事。

  1. 可以订阅主题,就像 observable 一样。
  2. 主题还可以订阅其他可观察对象。

话虽如此,主题和可观察对象之间存在一个主要区别。

一个主题的所有订阅者共享该主题的相同执行。即当一个主体产生数据时,它的所有订阅者都将收到相同的数据。这种行为与可观察对象不同,其中每个订阅都会导致可观察对象的独立执行。


推荐阅读