Angular的提供者:基于@Input()参数动态提供值
创始人
2024-10-24 10:30:56
0

为了基于 @Input() 参数动态提供值,我们可以使用 @Injectable() 装饰器来创建一个服务。在服务中,我们可以使用 BehaviorSubject 类来创建一个可观察对象,并在组件中订阅该对象。当 @Input() 参数值更改时,我们可以在服务中更新可观察对象,以提供新的值。

以下是示例代码:

生成服务:

import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs';

@Injectable() export class DataService { private messageSource = new BehaviorSubject('default message'); currentMessage = this.messageSource.asObservable();

constructor() { }

changeMessage(message: string) { this.messageSource.next(message) } }

在组件中订阅服务:

import { Component, OnInit, Input } from '@angular/core'; import { DataService } from '../data.service';

@Component({ selector: 'app-home', template: {{message}} , styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { @Input() name: string; message:string;

constructor(private data: DataService) { }

ngOnInit() { this.data.currentMessage.subscribe(message => this.message = message) }

newMessage() { this.data.changeMessage("Hello from home component") } }

在组件的 HTML 模板中使用 @Input():

当组件的 @Input() 值更改时,我们可以在组件中使用 changeMessage() 方法来更新服务中的数据。

以上就是基于 @Input() 参数动态提供值的Angular解决方法。

相关内容

热门资讯

透视软件!wepoker模拟器... 透视软件!wepoker模拟器哪个好用(透视)总是有挂(详细辅助攻略教程)辅助器中分为三种模型:软件...
透视app!wepoker免费... 透视app!wepoker免费透视(透视)一直有挂(详细辅助科技教程)一、软件透明挂的定义与意义1、...
透视最新!wepoker安装教... 透视最新!wepoker安装教程(透视)好像真的有挂(详细辅助实用技巧);1、下载好辅助软件之后点击...
透视有挂!wepoker私人局... 透视有挂!wepoker私人局辅助器怎么用(透视)好像存在有挂(详细辅助2025新版技巧)一、软件透...
透视科技!菠萝辅助器免费版的特... 透视科技!菠萝辅助器免费版的特点(透视)确实有挂(详细辅助曝光教程)1、透视辅助简单,软件透明挂操作...
透视了解!hhpoker真的假... 透视了解!hhpoker真的假的(透视)总是真的是有挂(详细辅助线上教程)1)辅助挂:进一步探索辅助...
透视脚本!wepoker透视挂... 透视脚本!wepoker透视挂底牌(透视)一直是真的有挂(详细辅助新2025教程);1、这是跨平台的...
辅助透视!pokemmo脚本辅... 辅助透视!pokemmo脚本辅助(透视)好像是真的有挂(详细辅助科技教程)1、ai辅助优化,发牌逻辑...
透视讲解!来玩app破解版(透... 透视讲解!来玩app破解版(透视)一直有挂(详细辅助辅助教程)辅助器中分为三种模型:软件透明挂、辅助...
透视ai代打!wepokerp... 透视ai代打!wepokerplus开挂(透视)真是存在有挂(详细辅助透视教程)1、操作简单,无需注...