2 回答

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
您還可以閱讀Angular Dependency Injection。要在某些組件中使用可注入服務(wù),您必須將其放入構(gòu)造函數(shù)并讓 Angular DI 提供它:AlertComponent 的 Costructor 應(yīng)該具有:
constructor ( private/proteced alertService:AlertService) {
alertService.subsribe ((par)=> {
this.add(par);
...})
}

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個(gè)贊
你有很多東西要學(xué)。這只是懶惰的例子,因?yàn)槊看味几采w可觀察的。這不是一個(gè)完美的代碼,但顯示了一點(diǎn)點(diǎn) Observables 是如何工作的。
警報(bào)服務(wù):
import {
Injectable
} from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AlertService {
alerts: Observable<any>
constructor() { }
success(message: any) {
this.alerts = of(message)
}
error(message: string) {
this.alerts = of(message)
}
}
警報(bào)顯示的警報(bào)組件:
export class AlertComponent implements OnInit {
dismissible = true;
// just inject service
constructor(public alerts$: AlertService) { }
ngOnInit() {
}
}
模板:
<div *ngIf="alerts$ | async as alerts"> <!-- | async is an pipe it will subscribe for you. importat for observables to first be in *ngIf then in *ngFor loops-->
<ng-container *ngFor="let item of alerts">
<alert[type]="alert.type"[dismissible]="dismissible" [dismissOnTimeout]="alert.timeout"> {{ item }}</alert>
</ng-container>
</div>
在您想要的任何組件中觸發(fā)警報(bào)的命令:
login() {
this.authService.login(this.model).subscribe(next => {
this.alert.success({ type: 'info', timeout: '5000', msg: "Success!"});
}, error => {
this.alert.failure({ type: 'info', timeout: '5000', msg: "Success!"}); // `this function u can delete meend failure just succes refactor to 'open'`
}, () => {
// do something else
});
}
關(guān)于服務(wù)您需要記住在app.module.ts或任何其他模塊中提供它們,providers: [AlertService]因此應(yīng)用程序?qū)⒅肋@是一項(xiàng)服務(wù)。然后你在你按班級(jí)的地方注射它們constructor()。注入時(shí),您需要始終為它們?cè)O(shè)置一個(gè)范圍,例如“私有公共或受保護(hù)”,否則您最終會(huì)在類型或服務(wù)類中使用常規(guī)變量。
關(guān)于 Observable:
有無窮無盡的 Observables,當(dāng)你訂閱它們時(shí),你需要在互聯(lián)網(wǎng)上的某個(gè)地方取消訂閱。| async如果變量是一個(gè)無限循環(huán),Pipe 會(huì)為你做這件事。
添加回答
舉報(bào)