![](/img/trans.png)
[英]How do I send data from a Component to another Component in Angular?
[英]In Angular 7 when passing data from one component to another, do I use a service and subscribe/listen in the receiving component?
我是 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>
您还可以阅读Angular 依赖注入。 要在某些组件中使用可注入服务,您必须将其放入构造函数并让 Angular DI 提供它: AlertComponent 的构造函数应该具有:
constructor ( private/proteced alertService:AlertService) {
alertService.subsribe ((par)=> {
this.add(par);
...})
}
你有很多东西要学。 这只是懒惰的例子,因为每次都可以覆盖观察。 这不是一个完美的代码,但稍微展示了 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]
这样应用程序就会知道这是一项服务。 然后您将它们注入到您通过 class constructor()
观察的地方。 注入时,您需要始终为它们设置 scope,例如“私有公共或受保护”,否则您最终会得到类型或服务 class 的常规变量。
关于 Observables:
有无穷无尽的 Observables,当你订阅它们时,你需要取消订阅,在互联网上的某个地方阅读它。 | async
如果变量是一个无限循环, | async
Pipe 将为您执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.