You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 11初始化时如何将localStorage取值作为参数传给其他函数

问题根因

你的猜测并不成立:of() 是RxJS的同步发射操作符,不存在resp还未完成获取就传入下游的问题。触发415错误的核心原因是:从localStorage中取出的值默认是字符串类型,而getBranchStock接口要求入参为数字类型,参数类型不匹配导致请求格式不符合后端要求,返回不支持的媒体类型错误。你直接传入固定数字45时类型符合要求,所以请求正常。

解决方案

1. 修正getBranchId方法,对返回值做类型转换

同时建议用标准的getItem方法读取localStorage,避免异常:

getBranchId(): Observable<number | null> {
  const branchId = localStorage.getItem('branch');
  // 将字符串转为数字,空值做兜底处理
  return of(branchId ? Number(branchId) : null);
}

2. 优化异步请求写法,避免嵌套订阅

用RxJS的switchMap操作符串联请求,同时把订阅加入统一管理的subs中,组件销毁时自动取消订阅避免内存泄漏:

populateTable() {
  this.subs.add(
    this.branchService.getBranchId()
      .pipe(
        // 过滤空值,避免发起无效请求,不需要可删除
        filter(branchId => !!branchId),
        // 串联请求,将上游的id作为参数发起第二个请求
        switchMap(branchId => this.branchService.getBranchStock(branchId))
      )
      .subscribe({
        next: (resp: any) => {
          // 处理返回结果
        },
        error: (error: HttpErrorResponse) => {
          console.log(error);
        }
      })
  );
}

如果localStorage中存储的branch存在非数字格式的场景,可以额外加格式校验逻辑,避免转换出NaN导致请求异常。


内容的提问来源于stack exchange,提问作者SeventhWarhawk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 05:45:04