Serviço de inserção angular no arquivo.html

Sep 09 2020

Estou usando o Angular 7 (e um dia terei que atualizar minha versão). Eu tenho um serviço que tem algumas variáveis que podem mudar de acordo com alguns Promise(http GET, PUT... resposta).

Desejo imprimir essas variáveis ​​em um modelo.

Posso fazer isso:

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.
            },
            () => {}
        );
    }

}

Desejo usar o serviço porque o algoritmo é igual a outros componentes, mas eles não podem ver as variáveis ​​de outros componentes. Portanto, não posso usar a assinatura com Assunto de comportamento e Observável:

Existem soluções melhores?

Respostas

1 ng-hobby Sep 09 2020 at 17:33

Não, não é best practicepara renderizar o resultado do serviço diretamente no modelo. É melhor injetar seu serviceas a dependency (injeção de dependência) em seu componente, o que define alguns variablesresultados de serviço e os renderiza em seu modelo. Então, tente algo assim:

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>