我只想第一次调用API,然后将保存的变量返回到服务中。我更改了代码,如下所示:
export class CategoryService {
categories: Category[]
constructor(private http: HttpClient, private handleError: HandleErrorService) {
}
/************ REST CALLS *****************/
/**
* Retrieve configuration categories
*/
private getListCategories() {
return this.http.get<Category[]>("/api/configuration/category").pipe(
map(res => {
this.categories = res;
return res;
}),
catchError(err => this.handleError.handleError(err, { severity: 'error', summary: 'Error retrieving the list of categories', life: 5000 })) // then handle the error;
);
}
/************ CATEGORY MANAGEMENT ************/
get getCategories() {
if (this.categories)
return this.categories;
else
this.getListCategories().subscribe((categories:Category[])=>{
return categories;
});
}
}但在我的getCategories中,我必须等待API调用的响应。是否有模式或最佳实践来实现我的目标?当然,我可以从组件中设置服务变量,但之后其他组件可能会调用API,而不是变量。
发布于 2019-06-06 23:22:03
不能从订阅中返回值。它是异步的。您有几个选项,比如将可观察对象转换为Promise并使用async/await,或者您可以返回一个可观察对象并让调用该服务的人订阅它。
示例:
get getCategories() {
if (this.categories)
return of(this.categories);
else
return this.getListCategories();
}然后在组件中调用getCategories()方法
this.categoryService.getCategories.subscribe( categories => {
//console.log(categories)
})看看这个blog post,作者解释了如何在Angular的服务中构建缓存机制。
发布于 2019-06-06 23:23:42
我倾向于使用一个可观察对象来保持订阅函数在这类事情的服务之外。
getCategories() {
return this.categories
? of(this.categories)
: this.getListCategories().do((categories:Category[]) => {
this.categories = categories;
});
}发布于 2019-06-06 23:23:42
尝试使用function localStorage来保存您的值,并在恢复它之后,直到您不关闭浏览器窗口。
localStorage.setItem("key","value")
//after you can get the value using
localStorage.getItem("key")不要忘记,getItem总是返回一个字符串,而setItem需要一个字符串作为值和键
https://stackoverflow.com/questions/56480534
复制相似问题