所以我有一个使用字典来存储 HTTP 响应的服务(将 id 映射到特定的 URL)。
import { HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class urlService {
private map: Map<string, string>;
constructor(private http: HttpClient) {
this.map = new Map<string, string>();
}
public getUrl(id: string): Observable<string> {
if (this.map.has(id)) {
return of(this.map.get(id));
}
this.http.get<any>(`...sampleURL...`)
.subscribe((result) => {
this.map.set(id, result.url);
return of(this.map.get(id));
});
}
}
但是,当我尝试从我的应用程序组件中获取这个
url
时,记录的值为undefined
。
this.urlService.getUrl(this.id).subscribe(
url => console.log(url)
);
我想这是因为在
urlService.getUrl()
。我有一个订阅返回Observable
。谁能指出我解决这个问题的正确方向?
我尝试使用
switchMap
,但这似乎对我没有帮助。
this.http.get<any>(`...sampleUrl...}`).pipe(
switchMap(result => {
this.map.set(id, result.url);
return of(this.map.get(id));
}))
.subscribe();
您没有正确返回当前
Observable
方法中的getUrl
。它没有任何返回值,因此返回undefined
.
相反,您应该使用
Observable
rxjs 运算符返回 map
。
import { map } from 'rxjs';
public getUrl(id: string): Observable<string> {
if (this.map.has(id)) {
return of(this.map.get(id));
}
return this.http.get<any>(`...sampleURL...`)
.pipe(
map((result) => {
this.map.set(id, result.url);
return this.map.get(id);
// Or
// return result.url;
})
);
}