为了账号安全,请及时绑定邮箱和手机立即绑定

在 Angular 7 中,当将数据从一个组件传递到另一个组件时,我是否使用服务并在接收组件中

在 Angular 7 中,当将数据从一个组件传递到另一个组件时,我是否使用服务并在接收组件中

森林海 2021-11-04 16:15:15
我是 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 显示的传入消息。前任。警报组件.tsexport 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>
查看完整描述

2 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

您还可以阅读Angular Dependency Injection。要在某些组件中使用可注入服务,您必须将其放入构造函数并让 Angular DI 提供它:AlertComponent 的 Costructor 应该具有:


constructor ( private/proteced alertService:AlertService) { 

   alertService.subsribe ((par)=> {

   this.add(par); 

   ...})

}


查看完整回答
反对 回复 2021-11-04
?
UYOU

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 会为你做这件事。


查看完整回答
反对 回复 2021-11-04
  • 2 回答
  • 0 关注
  • 131 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信