file.htmlのAngular挿入サービス
Sep 09 2020
私はAngular7を使用しています(そしていつかバージョンをアップグレードする必要があります)。私はいくつかに応じて変更することができますいくつかの変数持ってサービスしていPromiseます(http GET、PUT、...応答)。
これらの変数をテンプレートに出力したいと思います。
私はこれを行うことができます:
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.
},
() => {}
);
}
}
アルゴリズムは他のコンポーネントと同じですが、他のコンポーネントの変数を見ることができないため、サービスを使用したいと思います。したがって、BehaviorSubjectとObservableでサブスクリプションを使用することはできません。
より良い解決策はありますか?
回答
1 ng-hobby Sep 09 2020 at 17:33
いいえ、best practiceサービスの結果をテンプレートに直接レンダリングすることではありません。コンポーネントに(依存性注入)serviceとして注入し、サービス結果を設定してテンプレートにレンダリングすることをお勧めします。したがって、次のようなものを試してください。dependency variables
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>