2 回答

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

TA貢獻1878條經驗 獲得超4個贊
你有很多東西要學。這只是懶惰的例子,因為每次都覆蓋可觀察的。這不是一個完美的代碼,但顯示了一點點 Observables 是如何工作的。
警報服務:
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)
}
}
警報顯示的警報組件:
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>
在您想要的任何組件中觸發警報的命令:
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
});
}
關于服務您需要記住在app.module.ts或任何其他模塊中提供它們,providers: [AlertService]因此應用程序將知道這是一項服務。然后你在你按班級的地方注射它們constructor()。注入時,您需要始終為它們設置一個范圍,例如“私有公共或受保護”,否則您最終會在類型或服務類中使用常規變量。
關于 Observable:
有無窮無盡的 Observables,當你訂閱它們時,你需要在互聯網上的某個地方取消訂閱。| async如果變量是一個無限循環,Pipe 會為你做這件事。
添加回答
舉報