0

我正在使用 Angular 7(有一天我必须升级我的版本)。我有一项服务,其中一些变量可以根据某些变量Promise(http GETPUT、 ... 响应)而改变。

我希望在模板上打印这些变量。

我可以这样做:

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

}

我希望使用服务,因为算法等于另一个组件,但他们看不到其他组件的变量。因此,我不能将订阅与 Behavior Subject 和 Observable 一起使用:

有没有更好的解决方案?

4

1 回答 1

1

不,不是best practice将服务结果直接渲染到模板中。最好将您的serviceas dependency (Dependency Injection)注入到您的组件中,该组件使用服务结果设置一些variables并在模板中呈现它们。所以尝试这样的事情:

应用服务.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>
于 2020-09-09T17:33:02.460 回答