我有一个角度应用程序,应该在对服务器的API调用之后显示一组组件,其中服务器将根据用户的个人资料响应用户可以访问的组件。
我使用单独的服务来实现并处理和检索用户组件,并将其存储在服务本身中以便在Webapp内部轻松获取。
我的实现如下,
用于进行API调用的API服务,
api.service.ts
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 });
}
}
用于检索和存储与组件相关的信息的单独服务
station.service.ts
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();
}
}
和一个解析器,用于根据路由将必要的信息传递给组件。在这里,它调用station.service.ts以获取存储的值并使用api.service.ts进行必要的API调用
station.resolver.service.ts
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];
}
}
和站组件是使用服务的输入来处理要显示的组件。
station.component.ts
import {Component, Input, OnInit} from '@angular/core';
import {StationModel} from '../../models/station.model';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-station',
templateUrl: './station.component.html',
styleUrls: ['./station.component.scss']
})
export class StationComponent implements OnInit {
station: StationModel;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.route.data.subscribe((data) => {
this.station = data['station'];
});
console.log('*****params station', this.route.data['station']);
}
}
在模板中使用* 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可以毫无错误地加载组件)。>>
我想知道这是因为使用了解析器还是在我的实现中出现了问题?
对不起,如果我的问题不太清楚。如果有人能指出什么地方出了问题,将非常有帮助。
我有一个角度应用程序,应该在对服务器的API调用之后显示一组组件,其中服务器将根据用户的个人资料响应用户可以访问的组件。我...
尝试此操作:这是因为未定义可为空的变量工作站或未同步调用api。