首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 6将API调用保存到服务变量中

Angular 6将API调用保存到服务变量中
EN

Stack Overflow用户
提问于 2019-06-06 23:15:31
回答 3查看 91关注 0票数 0

我只想第一次调用API,然后将保存的变量返回到服务中。我更改了代码,如下所示:

代码语言:javascript
复制
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,而不是变量。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-06-06 23:22:03

不能从订阅中返回值。它是异步的。您有几个选项,比如将可观察对象转换为Promise并使用async/await,或者您可以返回一个可观察对象并让调用该服务的人订阅它。

示例:

代码语言:javascript
复制
get getCategories() {
    if (this.categories)
      return of(this.categories);
    else
      return this.getListCategories();
  }

然后在组件中调用getCategories()方法

代码语言:javascript
复制
this.categoryService.getCategories.subscribe( categories => {
   //console.log(categories)
})

看看这个blog post,作者解释了如何在Angular的服务中构建缓存机制。

票数 1
EN

Stack Overflow用户

发布于 2019-06-06 23:23:42

我倾向于使用一个可观察对象来保持订阅函数在这类事情的服务之外。

代码语言:javascript
复制
getCategories() {
  return this.categories
    ? of(this.categories)
    : this.getListCategories().do((categories:Category[]) => {
        this.categories = categories;
      });
}
票数 -1
EN

Stack Overflow用户

发布于 2019-06-06 23:23:42

尝试使用function localStorage来保存您的值,并在恢复它之后,直到您不关闭浏览器窗口。

代码语言:javascript
复制
localStorage.setItem("key","value")
//after you can get the value using 
localStorage.getItem("key")

不要忘记,getItem总是返回一个字符串,而setItem需要一个字符串作为值和键

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56480534

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档