加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 6 – HttpClient在服务中保留订阅,但将结果传递给组件

发布时间:2020-12-17 07:09:50 所属栏目:安全 来源:网络整理
导读:我有一个preject包含一个服务(获取数据)和一个组件(显示它). 我想在app.component.ts上将代码保持在最低限度. 在我的服务中: getPosts() { return this.http.get('https://jsonplaceholder.typicode.com/posts',httpOptions).subscribe( result = { return
我有一个preject包含一个服务(获取数据)和一个组件(显示它).

我想在app.component.ts上将代码保持在最低限度.

在我的服务中:

getPosts() {
    return this.http.get('https://jsonplaceholder.typicode.com/posts',httpOptions).subscribe(
      result => {
        return result;
        this.theData = result;
      },error => {
        return error;
      }
    );
  }

在我的app.component.ts中:

getPostsFromService() {
    this.myService.getPosts();
  }

但是,当然,我需要得到结果并将其传递给我的组件,但这样的事情是行不通的:

myData;

  ...


  getPostsFromService() {
    this.myData = this.myService.getPosts();
  }

所以,我的问题是,我该怎么做或者是否真的建议在我的组件上调用subscribe而不是在服务中?

解决方法

在新的 HttpClientModule中,JSON是假定的默认值,不再需要使用res.json()显式解析

您可以告诉HttpClient响应的类型,使输出更容易,更明显.

可以使用type参数完成响应的类型检查
创建一个接口

export interface Idata{
  userId:number;
  Id:number;
  title:string;
  body:string;
}

Http返回一个observable,我们可以告诉HttpClient.get将响应作为Idata类型返回当我们使用http.get< Idata []>(…)时,它返回Observable< Idata []>的实例.类型.
在您的服务中

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs';
import {Idata} from './Idata'
@Injectable()
export class ShareService {

    constructor(private httpc:HttpClient)
    {
    }

    public getPosts():Observable<Idata[]>
    {
        return this.httpc.get<Idata[]>('https://jsonplaceholder.typicode.com/posts');
    }
}

在您的组件中订阅Observable< Idata []>获取Idata的实例

public data:Array<Idata>=[];
  constructor(public service:ShareService)
  {
     this.service.getPosts().subscribe(value => {
        this.data=value;
     });
  }

另一种方法是使用异步管道
AsyncPipe接受一个observable或promise作为参数,调用subscribe或附加一个then处理程序,然后在将它传递给调用者之前等待异步结果.

public response:Observable<Idata[]>;
constructor(public service:ShareService)
{
    this.response=this.service.getPosts();
}

HTML

<div *ngFor="let item of (response|async)">
  {{item.body}}
</div>

LIVEDEMO

my question is,how can I do this or is it really recommended to call
subscribe on my component and not in the service?

It’s Good Practice to Delegate complex component logic to services

From Angular Style Guide
Do limit logic in a component to only
that required for the view. All other logic should be delegated to
services.

Do move reusable logic to services and keep components simple and
focused on their intended purpose.

Why? Logic may be reused by multiple components when placed within a
service and exposed via a function.

Why? Logic in a service can more easily be isolated in a unit test,
while the calling logic in the component can be easily mocked.

Why? Removes dependencies and hides implementation details from the
component.

Why? Keeps the component slim,trim,and focused.

在Component中订阅允许您与多个观察者共享一个http请求,如果您不这样做,则会违反DRY Principle
P:S
?要为多个观察者共享一个http请求,您需要像share这样的东西
操作符.

import {Observable} from 'rxjs';
import {share} from 'rxjs/operators'

export class dataService {

    public data$=Observable<Idata[]>
    constructor(http:HttpClient)
    {
        this.data$=this.http.get<Idata[]>('https://jsonplaceholder.typicode.com/posts').pipe(share());
    }
    public getPosts():Observable<Idata[]>
    {
        return this.data$
    }
}

This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one,then shares that subscription with all subsequent observers until the number of observers returns to zero,at which point the subscription is disposed.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读