据我了解,Redux 主要是为了在 javascript 应用程序中启用双向数据绑定。这对于非双向数据绑定的框架非常有用,例如 React。但为什么要在 Angular 中使用它,因为它本身就是双向数据绑定的?
为了说明我的问题,我在本机 Angular 中使用了代码来创建一个存储,以实现两个 Angular 组件之间的变量状态通信:
1) 商店
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StoreService {
customer: any;
constructor() { }
}
这个商店是一个原生的 Angular 服务,我只声明变量 customer(是的,打字会更好,但我想尽可能缩短它)。
2)异步api服务e
import { Injectable } from '@angular/core';
import { StoreService } from './store.service'
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor( private store: StoreService ) { }
getData() {
setTimeout(()=> {
this.store.customer = {
name: 'Bob',
age: 25
}
}, 2000);
}
}
这个api服务只有一个方法getdata()
异步检索客户数据。我可以用一个http.get
方法,在本例中是里面的代码setTimeout
将是中的代码next()
可观察订阅的功能。
请注意,我直接在前一个存储中实例化异步过程的返回。
3)使用store的组件
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service'
import { StoreService } from '../store.service'
@Component({
selector: 'app-mycomponent',
templateUrl: './mycomponent.component.html',
styleUrls: ['./mycomponent.component.css']
})
export class MycomponentComponent implements OnInit {
constructor(
private api: ApiService,
private store: StoreService
) { }
ngOnInit() {
this.api.getData();
}
}
请注意,除了导入服务存储和 api 之外,我只使用一行代码,即调用数据的代码。如果其他组件或任何其他服务已经填充了商店,则此行将毫无用处(请参阅下面的第二个组件)
4)组件的HTML模板
<ul>
<li>Name : {{store.customer?.name}}</li>
<li>Age : {{store.customer?.age}}</li>
</ul>
请注意,我直接使用模板中的存储来确保与也导入同一存储的其他组件进行双向数据绑定。
注意 elvis 运算符的使用?.
管理异步变量store.customer
.
5) 另一个修改 store 的组件
import { Component, OnInit } from '@angular/core';
import { StoreService } from '../store.service'
@Component({
selector: 'app-myothercomponent',
templateUrl: './myothercomponent.component.html',
styleUrls: ['./myothercomponent.component.css']
})
export class MyothercomponentComponent implements OnInit {
constructor(private store: StoreService) { }
}
我只导入商店,不需要任何其他代码行。
6)前一个组件的HTML模板
<p>
<input type="text" [(ngModel)]="store.customer && store.customer.name">
</p>
请注意由于使用 ngModel 而处理异步的特殊方法。顺便说一下,考虑在 dorder 中导入 FormsModule 来处理 HTML 中的输入。
现在更改第二个组件中客户名称的值,您将在第一个组件中看到其直接且瞬时的更改。
Angular 的这种双向数据绑定非常强大,而且设置和使用起来非常简单,我真的很想知道为什么我应该使用 Redux 或 NgRx。你能解释一下为什么我应该这样做吗?
感谢帮助。