Javascript 角度服务返回具有未定义值的可观测值
我有一个angular应用程序,它应该在对服务器进行API调用后显示一组组件,服务器将使用用户可以根据其配置文件访问的组件进行响应 我使用一个单独的服务来处理和检索用户组件,并将其存储在服务本身中,以便在webapp中轻松获取 我的执行情况如下: API服务进行API调用 api.service.tsJavascript 角度服务返回具有未定义值的可观测值,javascript,angular,typescript,angular-ui-router,Javascript,Angular,Typescript,Angular Ui Router,我有一个angular应用程序,它应该在对服务器进行API调用后显示一组组件,服务器将使用用户可以根据其配置文件访问的组件进行响应 我使用一个单独的服务来处理和检索用户组件,并将其存储在服务本身中,以便在webapp中轻松获取 我的执行情况如下: API服务进行API调用 api.service.ts import { Injectable } from '@angular/core'; import {HttpClient, HttpParams} from '@angular/common/
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {AuthService} from './auth.service';
import {Params} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class ApisService {
GET_BATCH_SCHEDULE = 'http://localhost:8000/getbatchplan';
GET_USER_STATIONS = 'http://localhost:7071/api/getUserStations';
GET_USER_LOCATIONS = 'http://localhost:7071/api/getUserLocations';
constructor(private httpClient: HttpClient, private authService: AuthService) { }
getCutplanBatches() {
return this.httpClient.get(this.GET_BATCH_SCHEDULE);
}
getStations(location: string) {
if (location === undefined){
console.log("undefined location call");
location = 'aqua';
}
const params = new HttpParams()
.set('email', this.authService.getAuthenticateduserInfo().displayableId)
.append('location', location);
return this.httpClient.get(this.GET_USER_STATIONS, { params: params });
}
getLocations() {
const params = new HttpParams()
.set('email', this.authService.getAuthenticateduserInfo().displayableId);
return this.httpClient.get(this.GET_USER_LOCATIONS, { params: params });
}
}
import {Injectable} from '@angular/core';
import {ApisService} from './apis.service';
import {StationModel} from '../models/station.model';
import {BehaviorSubject, Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class StationService {
userStations: BehaviorSubject<StationModel[]>;
userLocation: string;
constructor(private apiService: ApisService) {
this.userStations = new BehaviorSubject<StationModel[]>([]);
this.setLocationStations('aqua');
}
setLocation(location: string) {
this.userLocation = location;
}
getLocation() {
return this.userLocation;
}
setLocationStations(locationSelect: string) {
this.apiService.getStations(locationSelect).subscribe((data: StationModel[]) => {
this.userStations.next(data['stations']);
console.log('setting user locations:', this.userStations);
return this.userStations;
});
}
public getLocationStations(): Observable<StationModel[]> {
console.log('inside station service:', this.userStations);
console.log('inside station service loc:', this.userLocation);
return this.userStations.asObservable();
}
}
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs';
import {StationService} from '../../services/station.service';
import {Injectable} from '@angular/core';
import {StationModel} from '../../models/station.model';
@Injectable({
providedIn: 'root'
})
export class StationRouteResolver implements Resolve<StationModel> {
currentStation: StationModel;
constructor(private stationService: StationService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log('Resolves:', route.params['location']);
if (this.stationService.getLocation() === undefined) {
console.log('Initial setting:', route.params['location']);
this.stationService.setLocation(route.params['location']);
}else if (this.stationService.getLocation() !== route.params['location']) {
console.log('Changing location settings:', route.params['location']);
this.stationService.setLocation(route.params['location']);
}else{
console.log('Same location found!');
}
this.stationService.getLocationStations().subscribe((stations: StationModel[]) => {
console.log('observer resolver:', stations);
this.currentStation = stations.filter((station) => {
return station.stationPath === route.params['station'];
})[0];
console.log('----current station:', this.currentStation);
});
return this.currentStation;
// this.currentStation = this.stationService.getLocationStations().filter((station) => {
// return station.stationPath === route.params['station'];
//
// })[0];
}
}
用于检索和存储与组件相关的信息的独立服务
车站服务台
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {AuthService} from './auth.service';
import {Params} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class ApisService {
GET_BATCH_SCHEDULE = 'http://localhost:8000/getbatchplan';
GET_USER_STATIONS = 'http://localhost:7071/api/getUserStations';
GET_USER_LOCATIONS = 'http://localhost:7071/api/getUserLocations';
constructor(private httpClient: HttpClient, private authService: AuthService) { }
getCutplanBatches() {
return this.httpClient.get(this.GET_BATCH_SCHEDULE);
}
getStations(location: string) {
if (location === undefined){
console.log("undefined location call");
location = 'aqua';
}
const params = new HttpParams()
.set('email', this.authService.getAuthenticateduserInfo().displayableId)
.append('location', location);
return this.httpClient.get(this.GET_USER_STATIONS, { params: params });
}
getLocations() {
const params = new HttpParams()
.set('email', this.authService.getAuthenticateduserInfo().displayableId);
return this.httpClient.get(this.GET_USER_LOCATIONS, { params: params });
}
}
import {Injectable} from '@angular/core';
import {ApisService} from './apis.service';
import {StationModel} from '../models/station.model';
import {BehaviorSubject, Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class StationService {
userStations: BehaviorSubject<StationModel[]>;
userLocation: string;
constructor(private apiService: ApisService) {
this.userStations = new BehaviorSubject<StationModel[]>([]);
this.setLocationStations('aqua');
}
setLocation(location: string) {
this.userLocation = location;
}
getLocation() {
return this.userLocation;
}
setLocationStations(locationSelect: string) {
this.apiService.getStations(locationSelect).subscribe((data: StationModel[]) => {
this.userStations.next(data['stations']);
console.log('setting user locations:', this.userStations);
return this.userStations;
});
}
public getLocationStations(): Observable<StationModel[]> {
console.log('inside station service:', this.userStations);
console.log('inside station service loc:', this.userLocation);
return this.userStations.asObservable();
}
}
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs';
import {StationService} from '../../services/station.service';
import {Injectable} from '@angular/core';
import {StationModel} from '../../models/station.model';
@Injectable({
providedIn: 'root'
})
export class StationRouteResolver implements Resolve<StationModel> {
currentStation: StationModel;
constructor(private stationService: StationService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log('Resolves:', route.params['location']);
if (this.stationService.getLocation() === undefined) {
console.log('Initial setting:', route.params['location']);
this.stationService.setLocation(route.params['location']);
}else if (this.stationService.getLocation() !== route.params['location']) {
console.log('Changing location settings:', route.params['location']);
this.stationService.setLocation(route.params['location']);
}else{
console.log('Same location found!');
}
this.stationService.getLocationStations().subscribe((stations: StationModel[]) => {
console.log('observer resolver:', stations);
this.currentStation = stations.filter((station) => {
return station.stationPath === route.params['station'];
})[0];
console.log('----current station:', this.currentStation);
});
return this.currentStation;
// this.currentStation = this.stationService.getLocationStations().filter((station) => {
// return station.stationPath === route.params['station'];
//
// })[0];
}
}
使用模板中的*ngIf选择正确的组件
station.component.html
<app-batch-list-view *ngIf="station.stationType == 'o'"></app-batch-list-view>
<app-dashboard-view *ngIf="station.stationType == 'm'"></app-dashboard-view>
<app-print-view *ngIf="station.stationType == 'p'"></app-print-view>
问题是在启动和刷新页面时,特别是在station.component中,我得到一个变量未定义错误,因为
station.stationType未定义,应用程序从此中断
但是,如果我返回并返回到同一路线,这是可行的(使用ngif加载组件时没有任何错误)
我想知道这是因为使用了解析器还是我的实现中出现了错误
如果我的问题不太清楚,很抱歉。如果有人能指出问题所在,那将非常有帮助。试试这个:这是因为没有定义可为null的变量站或不同步调用api 对于第一个:
站:可为空
或
对于第二个:您可以在station.component.ts
中使用ngAfterViewInit()
而不是ngOnInit
尝试将这些station.stationType
更改为组件模板中的此station?.stationType
。哇,这就解决了!但根本原因可能是什么?是因为异步方法吗?是因为异步方法吗,是的。这是一个普遍的问题。