Biding on a variable which value comes from a service can't be seen

60 views Asked by At

In the beginning, I consume a service that gives me a string, I save it on variable and I use braces to show it on the HTML, but I don't see the value, I have tested the service and the value is coming from the backend, so I think the situation is due to the life cycle. I tried ngOnInit and ngAfterViewInit, but I can't get the value.

elCodigoInterno: string;

  ngOnInit() {
    this.iniciarFormulario();   

    this.dataService.getCodigoInterno().subscribe(
      //result => this.colaborador.codigoInterno = result,
      result => this.elCodigoInterno = result,
      error => console.log('error ', error)
    );       
  }

  ngAfterViewInit(){
    this.dataService.getCodigoInterno().subscribe(
      //result => this.colaborador.codigoInterno = result,
      result => this.elCodigoInterno = result,
      error => console.log('error ', error)
    ); 
  }

<label for="codigoInterno">Código Interno </label>      
<p>{{elCodigoInterno}} </p>
1

There are 1 answers

0
Ömer Özoğlu On

If you create a public variable in the dataService and then assign it to this variable in the getCodigoInterno method, you can get the value you want to get.

I can give an example

///// Service

export class LocationService {
  public locationlist: Location[] | any;
  public location: Location | any;
  constructor(private http: HttpClient) { }


  public getAllLocation(): Observable<Location[]> {
    return this.http.get<ApiResponse>(environment.locationApiUrl, {}).pipe(
      map(
        (response: ApiResponse) => {
          return this.locationlist = response.content;
        }
      )
    );
  }
}

///// Component

 public location;
      constructor(private locationService: LocationService) { }
    
      ngOnInit(): void {
        this.location = this.locationService.locationlist[0].id;
      }
      public getAlllocations() {
      this.locationService.getAllLocation().subscribe(location => {
      ...
      });
   }