Angular Service возвращает Observable с неопределенными значениями - PullRequest
0 голосов
/ 05 октября 2019

У меня есть угловое приложение, которое должно отображать набор компонентов после вызова API на сервере, где сервер будет отвечать компонентами, к которым пользователь может получить доступ, основываясь на его / ее профиле.

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

Моя реализация выглядит следующим образом:

Служба 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, используя api.service.ts

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>

Проблема в том, что я получаю переменную undefined ошибку при запуске и при обновлении страницы, в частности в station.component, потому что station.stationType не определени приложение перестает работать.

Однако это работает (компоненты загружаются без ошибок с помощью ngif), если я возвращаюсь и возвращаюсь по тому же маршруту.

Мне интересно, этоэто из-за использования преобразователя или что-то не так в моей реализации?

Извините, если мой вопрос не очень ясен. Если кто-то может указать, что не такбыть действительно полезным.

1 Ответ

0 голосов
/ 05 октября 2019

Попробуйте: это из-за того, что переменная станция не определена как nullable, или нет синхронизации api.

Для первого: station: Nullable<StationModel>

Или

Для второго: Вы можете использовать ngAfterViewInit() вместо ngOnInit в station.component.ts

...