我正在开发一个应向第三个Api发出http请求的应用。 当我进行身份验证过程时,Api为我提供了一个密钥 (它称为clientid),我必须将其与其他数据一起发布到将来 http请求。
因此,情况是在对Api进行身份验证之后,当我要发出任何其他请求时,我必须发布我从身份验证响应中获取的clientid。
我阅读了有关父子关系(@ input- @ output)的信息,但我认为这无济于事,因为该应用程序会从不同的组件发出不同的请求,而它们之间可能没有关系。
我的想法是,当我完成来自各个服务的认证过程时,我不得不将该字段存储在某个地方,以便在我想从我需要的任何配件中提出其他请求时可以使用。
我认为我需要类似单例的方法,但是我不确定 思想的适当性。
答案 0 :(得分:0)
您将要拥有一个发出请求并存储数据的服务。这是一个简单服务的示例,该服务通过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;
}));
}
}
然后,在您的角度组件中,它们都可以以完全相同的方式请求数据,但是只有首先执行请求的一个实际上会发出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);
});
}
}