Angular 6解决方案始终未定义

时间:2018-05-31 16:39:23

标签: javascript angular typescript rxjs

我正在尝试使用我的服务从数据库服务器获取值以在屏幕上显示。我使用解析器进行服务,因为数据库有时会有点慢。

但是数据this.route.data.subscribe给了我总是未定义的,没有我尝试过的matte。我检查了服务是否从服务器获得响应,确实如此。奇怪的是,如果我直接使用该服务,一切正常。

处理数据的组件:

import { Component, OnInit, Input } from '@angular/core';
import { TempsService, Temps } from '../../temps.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-temps',
  templateUrl: './temps.component.html',
  styleUrls: ['./temps.component.scss']
})
export class TempsComponent implements OnInit {
  @Input() solar: boolean;
  solarURL: string = 'tempSolar';
  waterURL: string = 'tempWater';
  tempSolar: number;
  tempWater: number;
  timestamp: string;

  temps: Temps;

  constructor(private route: ActivatedRoute,
  private tempService: TempsService) { }

  showWaterTemp() {
    this.tempService.getTemp(this.waterURL)
      .subscribe(data => {
        this.tempWater = data.rawValue;
        this.timestamp = data.time;
      });
  }

  showSolarTemp() {
    this.route.data
      .subscribe(data => {
        this.tempSolar = data.rawValue;
      });
  }
  ngOnInit() {
    if (this.solar) {
      this.showSolarTemp();
      this.showWaterTemp();
    }
  }
}

这是他的路由模块(我使用的是CreativeTim的NowUI Angular主题,因此大多数事情都是由他们完成的):

import { Routes } from '@angular/router';

import { DashboardComponent } from '../../dashboard/dashboard.component';
import { UserProfileComponent } from '../../user-profile/user-profile.component';
import { TableListComponent } from '../../table-list/table-list.component';
import { TypographyComponent } from '../../typography/typography.component';
import { IconsComponent } from '../../icons/icons.component';
import { MapsComponent } from '../../maps/maps.component';
import { NotificationsComponent } from '../../notifications/notifications.component';
import { TempsComponent } from '../../dashboard/temps/temps.component';
import { TempResolver } from '../../temp-resolver/temp-resolver.resolver';

export const AdminLayoutRoutes: Routes = [
    { path: 'dashboard',      component: DashboardComponent, children: [
        { path: '', component: TempsComponent, resolve: { temps: TempResolver } }
    ] },
    { path: 'user-profile',   component: UserProfileComponent },
    { path: 'table-list',     component: TableListComponent },
    { path: 'typography',     component: TypographyComponent },
    { path: 'icons',          component: IconsComponent },
    { path: 'maps',           component: MapsComponent },
    { path: 'notifications',  component: NotificationsComponent }
];

这就是解析器的样子:

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

@Injectable()
export class TempResolver implements Resolve<Temps> {

  test: number;
  constructor(private tempService: TempsService) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Temps> {
    this.tempService.getTemp('tempSolar').subscribe(data => {this.test = data.rawValue})
    alert(this.test)

    return this.tempService.getTemp('tempSolar');
  }
}

在我看来,这是一个非常奇怪的问题。

更新: 这是获取数据的服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TempsComponent } from './dashboard/temps/temps.component'

export interface Temps {
  id: string;
  time: string;
  date: string;
  name: string;
  rawValue: number;
}

@Injectable()
export class TempsService {

  constructor(private http: HttpClient) { }

  url: string = window.location.hostname;

  tempUrl = 'http://' + this.url + ':3000/latestTime/';

  getTemp(temp: String) {
    return this.http.get<Temps>(this.tempUrl + temp);
  }
}

3 个答案:

答案 0 :(得分:2)

我只是尝试将解决方案添加到使用Temp组件的仪表板组件中。而现在它就像一个魅力。 现在看起来像这样:

{ path: 'dashboard',      component: DashboardComponent, resolve: {temps: TempResolver} }

而不是:

{ path: 'dashboard',      component: DashboardComponent,
    children: [{ path: '', component: TempsComponent, resolve: { temps: TempResolver } }] 
},

答案 1 :(得分:1)

你能试试吗

   this.route.data
  .subscribe(({temps}) => {
    this.tempSolar = temps;
  });

答案 2 :(得分:0)

无论如何,请避免订阅getTemps()中的resolve(),只需返回Observable<whatever>即可。请记住getTemps()的异步性质。 alert(this.test)几乎总是在getTemps()完成之前执行,基本上保证在发出警报时它会undefined

只需返回getTemp(),即可返回Observable<Temps>

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> {
    return this.tempService.getTemp('tempSolar');
  }
}

然后在组件中根据需要提取rawValue属性:

showSolarTemp() {
  this.route.data.subscribe((data: { temps: Temps }) => {
    this.tempSolar = data.temps.rawValue;
  });
}

以下是显示功能的StackBlitz

希望这有帮助!