我是 Angular 7 的新手,我想知道我是否走在正确的道路上。
我有一个“警报”组件,它只在顶部的页面上显示一个 boostrap 警报框。我希望能够调用此警报并从任何组件显示它。
我很确定我需要一个服务,我可以调用它来传递消息,然后让警报组件订阅该服务以侦听传入的消息?
到目前为止,我可以调用该服务并向其传递一条“消息”,我只是不知道如何在警报组件中订阅/收听(我认为这是正确的术语)以侦听要显示的传入消息。
前任。登录组件
constructor(public authService: AuthService, private router: Router, private alert: AlertService) {}
login() {
this.authService.login(this.model).subscribe(next => {
this.alert.success('Logged in successfully');
}, error => {
this.alert.failure('Log in failed');
}, () => {
// do something else
});
}
然后这是我的服务
前任。警报服务
import {
Injectable
} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AlertService {
constructor() {}
success(message: string) {
// do something here?
}
error(message: string) {
// do something here?
}
}
然后我有我的 AlertComponent,但不确定我将如何订阅/监听从 AlertService 显示的传入消息。
前任。警报组件.ts
export class AlertComponent implements OnInit {
dismissible = true;
alerts: any[];
constructor() { }
ngOnInit() {
this.add();
}
// do something here to subscribe/listen to incoming messages from the service??
add(): void {
this.alerts.push({
type: 'info',
msg: `This alert will be closed in 5 seconds (added: ${new Date().toLocaleTimeString()})`,
timeout: 5000
});
}
}
和 html
<div *ngFor="let alert of alerts">
<alert [type]="alert.type" [dismissible]="dismissible" [dismissOnTimeout]="alert.timeout">{{ alert.msg }}</alert>
</div>
潇湘沐
UYOU
相关分类