Угловое разрешение 6 всегда неопределено - PullRequest
0 голосов
/ 31 мая 2018

Я пытаюсь использовать свой сервис для получения значений с сервера базы данных для отображения на экране.Я делаю это с распознавателем для службы, так как база данных иногда немного медленная.

Но данные this.route.data.subscribe всегда дают мне неопределенные значения, что я пробовал.Я проверил, получает ли служба ответ от сервера, и это делает.Странно то, что если я использую сервис напрямую, все работает нормально.

Компонент, в котором обрабатываются данные:

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();
    }
  }
}

Это модуль маршрутизации (я использую тему NowUI Angular отCreativeTim, так что большинство вещей было сделано ими):

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 голосов
/ 31 мая 2018

В любом случае, избегайте подписки на 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 , показывающий функциональность в действии.

Надеюсь, это поможет!

0 голосов
/ 01 июня 2018

Я только что попытался добавить разрешение к компоненту панели мониторинга, в котором используется компонент Temp.И теперь это работает как шарм.Теперь это выглядит так:

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

вместо этого:

{ path: 'dashboard',      component: DashboardComponent,
    children: [{ path: '', component: TempsComponent, resolve: { temps: TempResolver } }] 
},
0 голосов
/ 31 мая 2018

Можете ли вы попробовать это

   this.route.data
  .subscribe(({temps}) => {
    this.tempSolar = temps;
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...