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

我是 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>


森林海
浏览 132回答 2
2回答

潇湘沐

您还可以阅读Angular Dependency Injection。要在某些组件中使用可注入服务,您必须将其放入构造函数并让 Angular DI 提供它:AlertComponent 的 Costructor 应该具有:constructor ( private/proteced alertService:AlertService) {&nbsp;&nbsp; &nbsp;alertService.subsribe ((par)=> {&nbsp; &nbsp;this.add(par);&nbsp;&nbsp; &nbsp;...})}

UYOU

你有很多东西要学。这只是懒惰的例子,因为每次都覆盖可观察的。这不是一个完美的代码,但显示了一点点 Observables 是如何工作的。警报服务:&nbsp; &nbsp; import {&nbsp; &nbsp; Injectable} from '@angular/core';import { Observable, of } from 'rxjs';@Injectable({&nbsp; &nbsp; providedIn: 'root'})export class AlertService {&nbsp; &nbsp; alerts: Observable<any>&nbsp; &nbsp; constructor() { }&nbsp; &nbsp; success(message: any) {&nbsp; &nbsp; &nbsp; &nbsp; this.alerts = of(message)&nbsp; &nbsp; }&nbsp; &nbsp; error(message: string) {&nbsp; &nbsp; &nbsp; &nbsp; this.alerts = of(message)&nbsp; &nbsp; }}警报显示的警报组件:export class AlertComponent implements OnInit {&nbsp; &nbsp; dismissible = true;&nbsp; &nbsp; // just inject service&nbsp; &nbsp; constructor(public alerts$: AlertService) { }&nbsp; &nbsp; ngOnInit() {&nbsp; &nbsp; }}模板:<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-->&nbsp; &nbsp; <ng-container *ngFor="let item of alerts">&nbsp; &nbsp; &nbsp; &nbsp; <alert[type]="alert.type"[dismissible]="dismissible" [dismissOnTimeout]="alert.timeout"> {{ item }}</alert>&nbsp; &nbsp; </ng-container></div>在您想要的任何组件中触发警报的命令:login() {&nbsp; &nbsp; this.authService.login(this.model).subscribe(next => {&nbsp; &nbsp; &nbsp; this.alert.success({ type: 'info', timeout: '5000', msg: "Success!"});&nbsp; &nbsp; }, error => {&nbsp; &nbsp; &nbsp; &nbsp; this.alert.failure({ type: 'info', timeout: '5000', msg: "Success!"}); // `this function u can delete meend failure just succes refactor to 'open'`&nbsp; &nbsp; }, () => {&nbsp; &nbsp; &nbsp; // do something else&nbsp; &nbsp; });&nbsp; }关于服务您需要记住在app.module.ts或任何其他模块中提供它们,providers: [AlertService]因此应用程序将知道这是一项服务。然后你在你按班级的地方注射它们constructor()。注入时,您需要始终为它们设置一个范围,例如“私有公共或受保护”,否则您最终会在类型或服务类中使用常规变量。关于 Observable:有无穷无尽的 Observables,当你订阅它们时,你需要在互联网上的某个地方取消订阅。| async如果变量是一个无限循环,Pipe 会为你做这件事。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript