Я пытаюсь использовать свой сервис для получения значений с сервера базы данных для отображения на экране.Я делаю это с распознавателем для службы, так как база данных иногда немного медленная.
Но данные 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);
}
}