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

Angular 6 Resolver返回数据始终为undefined问题求助

问题排查与修复方案

我仔细梳理了你的代码,发现几个核心问题导致this.route.data.subscribe获取的数据为undefined,下面一步步给你修复:

1. 组件中错误访问Resolver返回的数据键名

你的路由配置里,resolve的关联键是temps:

resolve: { temps: TempResolver }

但在组件的showSolarTemp方法里,你直接尝试访问data.rawValue——这是错误的,Resolver返回的数据会被挂载在你定义的temps键下面,必须先取data.temps,再获取内部的属性。

修正后的组件方法:

showSolarTemp() {
  this.route.data.subscribe(data => {
    // 先打印完整data确认结构(调试用,后续可删除)
    console.log('Resolver返回的完整数据:', data);
    // 正确访问Resolver返回的Temps对象
    this.tempSolar = data.temps.rawValue;
    this.timestamp = data.temps.time; // 顺便同步时间字段
  });
}

2. 清理Resolver中的冗余异步代码

你的Resolver里写了一段多余的订阅逻辑:

this.tempService.getTemp('tempSolar').subscribe(data => {this.test = data.rawValue})
alert(this.test)

HTTP请求是异步的,alert(this.test)会在请求返回前执行,所以这里的弹窗永远是undefined,而且这段代码完全没必要——Resolver只需要直接返回服务的Observable即可,Angular会自动订阅并把数据注入到路由的data中。

优化后的Resolver:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Temps, TempsService } from '../temps.service';
import { Observable } from 'rxjs';

@Injectable()
export class TempResolver implements Resolve<Temps> {
  constructor(private tempService: TempsService) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Temps> {
    // 直接返回服务的Observable,Angular会处理后续订阅逻辑
    return this.tempService.getTemp('tempSolar');
  }
}

3. 确认Resolver已在模块中注册

这是极易遗漏的点:你需要把TempResolver添加到对应NgModule的providers数组里,否则Angular找不到这个Resolver,路由无法正常注入数据:

@NgModule({
  declarations: [TempsComponent, DashboardComponent],
  imports: [RouterModule.forChild(AdminLayoutRoutes)],
  providers: [TempResolver, TempsService] // 确保Resolver在此注册
})
export class AdminLayoutModule { }

4. 调试小技巧

如果还是有问题,可以在组件的ngOnInit里先打印路由快照数据,确认Resolver是否正常工作:

ngOnInit() {
  console.log('路由快照data:', this.route.snapshot.data);
  if (this.solar) {
    this.showSolarTemp();
    this.showWaterTemp();
  }
}

如果快照里有temps字段,说明Resolver已经正常返回数据,只是组件访问方式有误;如果没有temps,大概率是Resolver未注册或路由配置出错。

按照上述步骤修改后,应该就能正常获取Resolver返回的数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:54:04