【问题标题】:How can i share data from http Response between components?如何在组件之间共享来自 http 响应的数据?
【发布时间】:2019-09-20 23:43:55
【问题描述】:

我正在开发一个应用程序,它应该向第三个 Api 发出 http 请求。 当我进行身份验证过程时,Api 为我提供了一个密钥 (它称为clientid)我必须将其与其他数据一起发布到未来 http 请求。

所以情况是,在对 Api 进行身份验证后,当我想发出任何其他请求时,我必须发布我从身份验证响应中获取的 clientid。

我读到了父子关系(@input-@output),但我认为这没有帮助,因为应用程序会从不同的组件发出不同的请求,它们之间可能没有关系。

我的想法是,当我完成各个服务的身份验证过程时,我必须将此字段存储在某个地方,以便在我想从我需要的任何组件发出其他请求时可用。

我认为我需要类似单例的方法,但我不确定 思想的适当性。

【问题讨论】:

  • 你可以实现一个 http 拦截器并在 Post 请求中插入你的 clientid。共享服务可以保存您的 clientId,并且拦截器将其插入到您需要的请求中

标签: angular typescript variables components global


【解决方案1】:

您将需要一个发出请求并存储数据的服务。下面是一个简单服务的示例,它对一些字符串数组的数据发出 HTTP 请求。

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

Injectable({
    providedIn: 'root'
})
export class MyExampleService {
    private myData: string[] = [];

    constructor(private readonly http: HttpClient) { }

    getData$(): Observable<string[]> {
        //if we already got the data, just return that
        if (this.myData.length > 0) {
            return of(this.myData);
        }

        //if not, get the data
        return this.http.get<string[]>('http://my-api.com/get-stuff')
            .pipe(tap((returnedData: string[]) => {
                //save the returned data so we can re-use it later without making more HTTP calls
                this.myData = returnedData;
            }));
    }
}

然后在您的 Angular 组件中,它们都可以以完全相同的方式请求数据,但只有首先执行此操作的组件才会真正发出 HTTP 请求,其他组件只会获取已缓存的数据。

import { Component, OnInit } from '@angular/core';
import { MyExampleService } from '../services/my-example.service';

@Component({
    selector: 'app-my-example',
    templateUrl: './my-example.component.html'
})
export class MyExampleComponent implements OnInit {
    theData: string[] = [];

    constructor(private readonly myExampleService: MyExampleService) {}

    ngOnInit(): void {
        //call the service
        this.myExampleService.getData$()
            .subscribe((data: string[]) => {
              //when sucessful, data is returned here and you can do whatever with it
              this.theData = data;
            }, (err: Error) => {
                //When unsuccessful, this will run
                console.error('Something broke!', err);
            });
    }
}

【讨论】:

  • 非常感谢您的回答,我用您的示例解决了问题。如果我是对的,您的示例使用了依赖注入的思想!
猜你喜欢
  • 2020-08-31
  • 2021-10-12
  • 1970-01-01
  • 2016-06-10
  • 2016-06-23
  • 2018-05-15
  • 1970-01-01
相关资源
最近更新 更多