angular - 订阅 Observable 与订阅 Subject

标签 angular firebase angular2-services

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

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

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

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

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() {
    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[]);
  }
}

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

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();
  }
}

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

最佳答案

We can say that Subject is a special type of Observable.

Observable:订阅它以获取值。

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

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

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

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

另一方面,Subject 可以同时充当 - 数据生产者和数据消费者

这意味着两件事。

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

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

All subscribers to a subject share the same execution of the subject. i.e. when a subject produces data, all of its subscribers will receive the same data. This behavior is different from observables, where each subscription causes an independent execution of the observable.

关于angular - 订阅 Observable 与订阅 Subject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57636203/

相关文章:

templates - Angular2 模板 : how to wrap contents of ngFor with DIV

android - 如何将数据字段保存到 Firebase 用户输入

ios - 手动屏幕跟踪在 Firebase (iOS) 中不起作用

angular - 带有可选负载的 ngrx 操作

angular - Ngx-translate 给出 404 错误 Nativescript angular

android - 当应用程序处于后台状态时,Google FCM getIntent 不返回预期数据

node.js - 如何以正确的方式从response.body中获取数据?

angular - 获取服务中的第一个路由参数

angular - 路由到另一个组件后,服务返回时通知用户

Angular Testing 抛出错误