简体   繁体   中英

Angular Issue - trying to Access a variable from a service in a component

Apologizes I am very new to typescript. I have two components and one service. One component uses a backend API to retrieve some numbers to display in a kendo-combobox. A search button has been implemented that takes the selected number in the combobox and makes another API call. My second component should then display the results of the second API call in a kendo-grid.

My problem is that my second screen does not log the results of the API (I'm using logging the API result to console for now).

Code Below:

Parent Component:

import { BreadcrumbPath } from '../../shared/breadcrumb/model/breadcrumb-path';
import { BreadcrumbService } from '../../shared/breadcrumb/services/breadcrumb.service';
import { Observable, observable } from 'rxjs';
import { EngineMoveClient, Engine } from './../../api-clients/api';
import { map } from 'rxjs/operators';
import { CorrectEngineMoveFilterComponent } from '../correct-engine-move-filter/correct-engine-move-filter.component';
import { CorrectEngineMoveService } from '../correct-engine-move.service';
import { untilDestroyed } from 'ngx-take-until-destroy';

@Component({
  selector: 'app-correct-engine-move',
  templateUrl: './correct-engine-move.component.html'
})
export class CorrectEngineMoveComponent implements OnInit, OnDestroy {

  esnNumbers$: Observable<string[]>;

  @Input()
  engineInfo$ : Observable<{ EPN: string;
                 ESN: string;
                 ER: string;
                 DN: string;
                 DIN: string;
                 EL: string; }[]>;

  public selectedEsn;

  public tempEngineInfo$ = [];
  constructor(
    private breadcrumbService: BreadcrumbService,
    private engineMoveClient: EngineMoveClient,
    private correctEngineMoveService : CorrectEngineMoveService
  ) {
  }

  ngOnInit() {
    this.registerBreadCrumb();
  }

  ngAfterInit() {
    this.correctEngineMoveService.engineInfoSubject.subscribe( res => { this.tempEngineInfo$.push(res) 
      console.log(this.tempEngineInfo$) } )
  }
  ngOnChanges() {
  }

  ngOnDestroy() {}

  registerBreadCrumb(): void {
    const breadcrumb = BreadcrumbPath.correctEngineMoveDefaultItem;
    breadcrumb.path = null;

    this.breadcrumbService.setBreadcrumb(breadcrumb);
  }

  setSelectedESN(value) {
    this.selectedEsn = value;
  }

  public onBlur() { } // workaround for blur detection

  logCheck() {
    this.correctEngineMoveService.engineInfo$.subscribe( res => { this.tempEngineInfo$.push(res) 
      console.log(this.tempEngineInfo$) } )
  }
}

Child Component:

import { Component, OnInit,OnDestroy } from '@angular/core';
import { FormStateService } from '../../core/services/form-state/form-state.service';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { DateValidator } from '../../validation/date-validator';
import { CorrectEngineMoveService } from '../correct-engine-move.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-correct-engine-move-filter',
  templateUrl: './correct-engine-move-filter.component.html',
  providers : [CorrectEngineMoveService] 
})
export class CorrectEngineMoveFilterComponent implements OnInit, OnDestroy {

  constructor( 
    private formBuilder: FormBuilder,
    private correctEngineMoveService: CorrectEngineMoveService
    ) { }

  engineMoveFilters: FormGroup;
  correctEngineMoveFilters: FormGroup;
  esnNumbers$ : Observable<string[]>;
  selectedEsn : string;

  ngOnInit() {
    this.buildForm();
    this.getESN();
  }

  ngOnDestroy() {
  }

  private getESNNumbers() {
    this.esnNumbers$ = this.correctEngineMoveService.getESN();
  }

  setSelectedESN(value) {
    this.selectedEsn = value;
  }

  loadInfoForESN() {
    this.correctEngineMoveService.setInfoFromESN(this.selectedEsn);
  }

  public onBlur() { } // workaround for blur detection

  private buildForm() {
      this.correctEngineMoveFilters = this.formBuilder.group({
          aircraftTailNumber: this.formBuilder.control(null, Validators.required)
      }, {
      });
  }
}

Service

import { Injectable, Output } from '@angular/core';
import * as moment from 'moment';
import { BehaviorSubject, Observable } from 'rxjs';
import { switchMap, tap, map } from 'rxjs/operators';
import { EngineMoveClient } from '../../app/api-clients/api';

import { CorrectEngineMoveComponent } from './correct-engine-move/correct-engine-move.component';

// This class holds methods that allow correct engine move componants
// to call Api's and transfer data between each other
@Injectable()
export class CorrectEngineMoveService {

    public engineInfoSubject = new BehaviorSubject<{ EPN: string;
        ESN: string;
        ER: string;
        DN: string;
        DIN: string;
        EL: string; }[]>( "" as any
        );



    @Output()
    engineInfo$ = this.engineInfoSubject.asObservable();

    constructor(
        private engineMoveClient: EngineMoveClient,
    ) {
    }

    public getESNNumbers() : Observable<string[]> {
        return this.engineMoveClient.getESN();
    }

    public setInfoFromESN(selectedEsn: string)
    {   
        let tempEngineInfo =  this.engineMoveClient.getEngine(selectedEsn).pipe(map(v => {
          return [
            {
                'EPN': v.EPN,
                'ESN': v.ESN,
                'ER': v.ER,
                'DN': v.DN,
                'DIN': v.DIN,
                'EL': v.EL
            }];
        }));
        tempEngineInfo.subscribe(a => {
            console.log(a)
            this.engineInfoSubject.next(a)

            this.engineInfo$ = this.engineInfoSubject.asObservable();
            this.engineInfo$.subscribe(a => console.log(a))         
        }
        )
    }
}

So just to clarify I want this.engineInfo$ in the service to be displayed in the Parent component specifically,

  logCheck() {
    this.correctEngineMoveService.engineInfo$.subscribe( res => {
      this.tempEngineInfo$.push(res) 
      console.log(this.tempEngineInfo$) 
    })
  }

Any help would be greatly appreciated.

I believe the problem is that in both the Panel Component and Child Component you have in the contructors:-

    private correctEngineMoveService: CorrectEngineMoveService

This will create 2 instances on the service. You can check this by adding a console message to the service constructor. So one will call the server and the other will be subcribed to.

You need to re-write to find a way to have 1 instance of the Service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM