String Angular 5在另一个变量更改时自动更新字符串变量
当另一个变量更改时,是否有方法更新字符串变量?我有一个使用各种变量构建的字符串。我使用插值在组件的html文件中显示该字符串。但是,如果字符串用于构建自身的变量发生更改,则字符串将永远不会更改,因为它们是不可变的。唯一的方法是在其他变量之一更改时再次重置字符串 示例ts代码:String Angular 5在另一个变量更改时自动更新字符串变量,string,angular,angular5,interpolation,String,Angular,Angular5,Interpolation,当另一个变量更改时,是否有方法更新字符串变量?我有一个使用各种变量构建的字符串。我使用插值在组件的html文件中显示该字符串。但是,如果字符串用于构建自身的变量发生更改,则字符串将永远不会更改,因为它们是不可变的。唯一的方法是在其他变量之一更改时再次重置字符串 示例ts代码: import { Component} from '@angular/core'; @Component({ selector: 'app-test-component', templateUrl: '.
import { Component} from '@angular/core';
@Component({
selector: 'app-test-component',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent {
myString = '';
amount = 0;
constructor() {
this.myString = `Hello, you have ${this.amount} dollars.`;
setTimeout(() => {
this.amount = 40;
}, 5000);
}
}
<p>{{ myString }}</p>
示例html代码:
import { Component} from '@angular/core';
@Component({
selector: 'app-test-component',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent {
myString = '';
amount = 0;
constructor() {
this.myString = `Hello, you have ${this.amount} dollars.`;
setTimeout(() => {
this.amount = 40;
}, 5000);
}
}
<p>{{ myString }}</p>
{{myString}
当然,五秒钟后,字符串保持不变,因为我从未重新初始化它。是否有一种方法可以自动检测myString
中使用的任何变量是否更改,然后更新myString
以使用更改的变量值
谢谢,欢迎提供任何信息 您可以使用BehaviorSubject来实现,它有一个“当前值”的概念。它存储向其使用者发出的最新值,并且每当新的观察者订阅时,它将立即从BehaviorSubject接收“当前值” 为金额数据创建单独的服务 服务.ts
//set the initial value here
amount=new BehaviorSubject(0);
组件。ts
//set the initial value here
amount=new BehaviorSubject(0);
变换检测器
如果模型中有任何东西(
您的类)已更改,但它没有反映视图,您可能会
需要通知Angular以检测这些更改(检测本地更改)
并更新视图
此处的示例:是否要在五秒钟后检测更改否,这只是示例代码<代码>此。金额将在代码的其他各个部分发生变化。我只是想举一个例子,说明我正在努力实现的目标(当金额发生变化时,
myString
仍然将amount
的原始值设置为0)。我试图阻止自己在代码的多个位置更新字符串,并希望有一种方法,myString
可以检测它正在使用哪些变量,如果有任何更改,则更新字符串以保留新值。如果在模板中使用“amount”作为插值,然后它会自动更新。@FranklinPious是的,但是我必须将它连接到模板中的字符串,这是我试图避免的。