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 会为你做这件事。
添加回答
举报