我仍处于学习 Angular 4 和 Redux 的早期阶段。我有一个从商店获取信息的组件。它在 View 中工作正常。但是当我尝试从组件内部访问相同的信息时,我得到的是一个对象而不是值。
这是我的组件:
import { Component } from '@angular/core';
import { NgRedux, select } from 'ng2-redux';
import { AppState } from '../../reducers/reducer';
import { QuizService } from '../../services/quiz.service';
import { clearQuiz } from '../../actions/actions';
@Component({
selector: 'quiz',
templateUrl: './quiz.component.html',
styleUrls: ['./quiz.component.css']
})
export class Quiz {
constructor(private ngRedux: NgRedux<AppState>, private service: QuizService) {}
@select('currentQuiz') currentQuiz;
@select('quizLength') quizLength;
@select('sessionId') sessionId;
handleClose() {
console.log("CLOSE", this.sessionId )
this.service.deleteSession(this.sessionId)
.subscribe(res => {
this.ngRedux.dispatch(clearQuiz())
})
, error => {
console.error(error);
}
}
}
“console.log("CLOSE", this.sessionId )”行不返回存储在存储中的值。相反,我得到这个:
CLOSE AnonymousSubject {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false, …}
如何从类中的这些对象中获取数据?在 View 中,如果我在值后添加“| async”,它们就会显示出来。但我无法从实际组件类中获取值。帮助!
最佳答案
您必须订阅状态的选定切片,因为当您从商店中@select
时,您得到的不是值,而是Observable
。这就是您必须在模板中使用 async
管道的原因。它会自动为您进行订阅。
例如,您可以在 OnInit
Hook 中订阅并将其分配给一个字段。如果字段是 Observables,最好给字段加上后缀 $
。我假设您有一个用于currentQuiz
数据模型的接口(interface)IQuiz
。如果变量名称与存储属性相同(忽略 $),则可以使用 @select
省略它:
@select() currentQuiz$: Observable<IQuiz>;
currentQuiz: IQuiz;
// ...
ngOnInit() {
this.currentQuiz$.subscribe(currentQuiz => this.currentQuiz = currentQuiz)
}
当您的商店更新时,this.currentQuiz
将自动重新分配。
关于Angular 4 Redux 选择问题(基本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49200350/