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

问题描述 投票:0回答:1

我是Angular 7的新手,我想知道自己是否在正确的道路上。

我有一个“警报”组件,该组件仅在顶部页面上显示boostrap警报框。我希望能够调用此警报并从任何组件中显示它。

我很确定我需要一个可以调用以传递消息的服务,然后使警报组件订阅该服务以侦听传入的消息?

到目前为止,我可以调用该服务并将其传递为“消息”,我只是不知道如何在警报组件中订阅/收听(我认为这是正确的术语),以侦听要显示的传入消息。

EX。 LoginComponent

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
  });
}

然后这是我的服务

EX。 AlertService

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的传入消息。

EX。 AlertComponent.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>
javascript angular typescript angular-services angular-observable
1个回答
0
投票

您也可以阅读Angular Dependency Injection。为了在某​​些组件中提供可注射服务,您必须将其放置在构造函数中,并让Angular DI提供它:AlertComponent的构造函数应具有:

constructor ( private/proteced alertService:AlertService) { 
   alertService.subsribe ((par)=> {
   this.add(par); 
   ...})
}

0
投票

您有很多知识要学习。这只是一个懒惰的例子,因为每次都可以覆盖。这不是一个完美的代码,但显示了一点可观察的工作原理。

警报服务:

    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)
    }
}

显示警报的Allert组件:

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.tsproviders: [AlertService]之类的任何其他模块中提供它们,因此应用程序将知道这是一项服务。然后按类constructor()将它们注入您所在的位置。注入时,您需要始终为它们设置一个范围,例如“ private public或protected”,否则您将在类型或服务类中得到常规变量。

关于可观察物:

有无穷无尽的Observable,当您订阅它们时,需要在互联网上的某个地方自动取消订阅以阅读它。 | async如果变量是一个无限循环,管道将为您完成此任务。

© www.soinside.com 2019 - 2024. All rights reserved.