Servicio de inserción angular en el archivo.html

Sep 09 2020

Estoy usando Angular 7 (y un día tengo que actualizar mi versión). Tengo un servicio que tiene algunas variables que pueden cambiar según algunos Promise(http GET, PUT... la respuesta).

Deseo imprimir estas variables en una plantilla.

Puedo hacer esto:

app.component.html:

<ng-container *ngIf="this.dogService.isWarningProblem">
    <ngb-alert [dismissible]="false" type="warning" style="text-align: center">
        {{this.dogService.errorMessage}}
    </ngb-alert>
</ng-container>

app.service.ts:

export class DraftService {

    public errorMessage: string;
    public isWarningProblem: boolean;

    constructor
        (
            private generalErrorService: GeneralErrorService,
            private http: HttpClient
        ) {
            [...]
        }

    public launchPingEditReadDraftByActionOfferIdUrl(action: string, offerIdUrl: string): Subscription {
        return interval(10).subscribe(
            () => {
                //Get variables from the server and set them.
            },
            () => {}
        );
    }

}

Deseo usar el servicio porque el algoritmo es igual a otros componentes pero no pueden ver las variables de otros componentes. Entonces, no puedo usar la suscripción con Behavior Subject y Observable:

¿Existen mejores soluciones?

Respuestas

1 ng-hobby Sep 09 2020 at 17:33

No, no se trata best practicede representar el resultado del servicio directamente en la plantilla. Es mejor inyectar su servicecomo dependency (Inyección de dependencia) en su componente, lo que establece algunos variablescon el resultado del servicio y los representa en su plantilla. Así que prueba algo como esto:

app.service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class DraftService {

    private errorMessage$ = new Subject<string>(); private isWarningProblem$ = new Subject<boolean>();

    
    constructor (
      private generalErrorService: GeneralErrorService,
      private http: HttpClient
    ) {
       this.launchPingEditReadDraftByActionOfferIdUrl();
    }

    sendErrorMessage(message: string) {
        this.errorMessage$.next({ text: message }); } clearErrorMessages() { this.errorMessage$.next();
    }

    onErrorMessage(): Observable<any> {
        return this.errorMessage$.asObservable();
    }

    public launchPingEditReadDraftByActionOfferIdUrl (action: string, offerIdUrl: string): Subscription {
      interval(10).subscribe(
        (res) => {
          this.sendErrorMessage(res.errorMessage);
          // The other like this
        });
    }
}

app.component.ts

import { Component } from '@angular/core';
import { DraftService } from './draft-service';

@Component({
  selector: 'app-template',
  templateUrl: './template.component.html',
  styleUrls: ['./template.component.css'],
})
export class TemplateComponent {

  public errorMessage: string;
  public isWarningProblem: boolean;

  constructor(
    private _draftService: DraftService,
  ) { }
   
  ngOnInit() {
    this._draftService.onErrorMessage().subscribe(
      res => {
        this.errorMessage = res
        //The other like this
      }
    );
  }
}

app.component.html

<ng-container *ngIf="isWarningProblem">
  <ngb-alert [dismissible]="false" type = "warning" style="text-align: center">
    {{errorMessage}}
  </ngb-alert>
</ng-container>