Angular - 使用由回调函数设置的服务属性在另一个组件中使用
创始人
2024-10-14 22:30:44
0

要在一个组件中使用由回调函数设置的服务属性,你可以通过以下步骤实现:

  1. 首先,创建一个名为data.service.ts的服务文件并定义一个属性和一个回调函数:
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private data: string;
  private callback: (data: string) => void;

  setData(data: string) {
    this.data = data;
    if (this.callback) {
      this.callback(data);
    }
  }

  registerCallback(callback: (data: string) => void) {
    this.callback = callback;
  }
}
  1. 然后,创建一个名为component1.component.ts的组件文件,在该组件中注册回调函数并使用服务属性:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-component1',
  template: `
    

Component 1

`, }) export class Component1Component implements OnInit { constructor(private dataService: DataService) {} ngOnInit() {} setData() { this.dataService.setData('Hello from Component 1'); } }
  1. 接下来,创建一个名为component2.component.ts的组件文件,在该组件中订阅服务属性的变化:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-component2',
  template: `
    

Component 2

Data: {{ data }}

`, }) export class Component2Component implements OnInit { data: string; constructor(private dataService: DataService) {} ngOnInit() { this.dataService.registerCallback(this.updateData.bind(this)); } updateData(data: string) { this.data = data; } }
  1. 最后,将这两个组件添加到你的模块中:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { Component1Component } from './component1.component';
import { Component2Component } from './component2.component';
import { DataService } from './data.service';

@NgModule({
  declarations: [AppComponent, Component1Component, Component2Component],
  imports: [BrowserModule],
  providers: [DataService],
  bootstrap: [AppComponent],
})
export class AppModule {}

现在,当你在Component1Component中点击按钮时,服务属性将被更新,并且Component2Component中的数据也会相应更新。

相关内容

热门资讯

技术分享!xpoker怎么作弊... 技术分享!xpoker怎么作弊,wepoker私人局俱乐部辅助,透明挂教程(有挂透视);人气非常高,...
重大通报!pokerworld... 此外,数据分析德州(pokerworld破解版下载)辅助神器app还具备辅助透视行为开挂功能,通过对...
终于知道!wepokerplu... 终于知道!wepokerplus万能挂,wepoker线上大神,辅助教程(有挂辅助);1.wepok...
推荐一款!epoker透视底牌... 1、推荐一款!epoker透视底牌,wepoker有脚本吗,德州教程(有挂攻略);详细教程。2、we...
总算了解!wepoker养号规... 1、总算了解!wepoker养号规律,we poker免费辅助器,曝光教程(有挂方法);详细教程。2...
一起来讨论!哈糖大菠萝万能挂,... 一起来讨论!哈糖大菠萝万能挂,聚星ai辅助工具收费多少,揭秘教程(有挂技巧)1、不需要AI权限,帮助...
让我来分享经验!wepoker... 让我来分享经验!wepoker游戏安装教程,wpk辅助插件,必赢教程(有挂神器);大神普及一款德州a...
免费测试版!xpoker辅助怎... 您好,wepoker钻石怎么看底牌这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302...
新手必备!pokemmo辅助脚... 新手必备!pokemmo辅助脚本,We poker辅助器下载,2025新版教程(有挂辅助),支持语音...
实测揭晓!wepoker插件辅... 实测揭晓!wepoker插件辅助,pokerworld辅助器,揭秘教程(有挂辅助);1分钟了解详细教...