【问题标题】:Benefit of async pipe vs traditional subscription异步管道与传统订阅的优势
【发布时间】:2022-02-15 01:21:43
【问题描述】:

根据我对异步管道的理解,它是一种以更少行订阅 observable 的更快方式。但是,我试图了解在什么情况下需要通过传统订阅(例如下面的当前组件)使用它?

import { Component, OnInit } from '@angular/core';
import { HttpService } from "./services/http.service";
import { Main } from "./interfaces/data-interface";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(private httpService: HttpService) {
  }

  mainData: Main;
  itemIndexFocus: number = 0;


  ngOnInit() {

    this.httpService.getFighterDetail()
            .subscribe((res) => {
              this.mainData = res.body;
            });
  }
}

http服务文件:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from 'rxjs';

@Injectable()
export class HttpService {

    constructor(private http: HttpClient) { }

    getFighterDetail(): Observable<any> {
        return this.http.get("/MYAPI", { responseType: 'json', observe: 'response' })
    }


}

这只是我总是可以使用异步管道的情况吗?如果我使用来自 api 的值填充响应式表单,那么我想我上面的组件的方法会更有益。

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以从阅读this开始。

    Http 是一个 observable,一旦收到响应就会自动完成,因此在其上使用异步管道是无稽之谈。

    NgRx 的异步管道非常强大。 Here 你可以找到几行关于订阅与异步管道的信息

    【讨论】:

      【解决方案2】:

      管道用于修改数据/向可观察对象添加额外的逻辑和其他有趣的东西。管道不会“订阅”可观察对象

      是的,你绝对不能使用管道,但是你错过了它们提供的功能和更简洁的代码

      例如,如果您有一些用户服务从您的 API 获取用户列表,那么您还必须考虑服务器何时不可用或返回错误代码。

      假设多个组件使用此用户服务,您想为所有组件添加错误处理吗?这很混乱。或者,在服务中,您可以通过管道处理错误

      这样每个需要用户的组件都不必关心错误处理

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-14
        • 2016-12-25
        • 2019-05-06
        • 2020-11-13
        • 1970-01-01
        • 2021-11-04
        • 2017-11-30
        相关资源
        最近更新 更多