在组件中设置可观察对象中的变量

Setting a variable in the component from an observable

提问人:user21559858 提问时间:4/4/2023 最后编辑:user21559858 更新时间:4/4/2023 访问量:43

问:

我正在尝试使用匿名函数将组件中的变量绑定到 subscribe() 函数中可观察对象的内容:

ngOnInit() {
    this.strSub = this._store.select(selectStr).subscribe((data) => console.log(data));
    //this.strSub = this._store.select(selectStr).subscribe((data) => {this.str = data});
}

未注释的行运行良好,而注释行在编译时抛出错误。Type 'void' is not assignable to type 'string'.

换句话说,此任务以某种方式破坏了程序。我怀疑这可能是由于在运行时的某个时候为 null,我添加了一个检查,但它仍然无法编译。this.str = datadataif (data) {...}

我见过人们以这种方式在组件中绑定变量(所以这应该是解决这个问题的有效方法),但不明白为什么这里不允许这样做。

下面是此示例的完整代码,它由一个带有 selectors.ts、reducer.ts 和 actions.ts 的 component.ts 组成:

组件.ts

export class AppComponent implements OnInit{
    constructor(private _store: Store) {}
    strSub: Subscription;
    str: string;
    numChanged: number;
    observable: Observable<string>;

ngOnInit() {
    this.strSub = this._store.select(selectStr).subscribe((data) => console.log(data));
    //this.strSub = this._store.select(selectStr).subscribe((data) => {this.str = data});
    // this.observable = this._store.select(selectStr)
}
}

选择器.ts

export const myTopLevelSelector = createFeatureSelector<fromReducer.State>(fromReducer.featureKey);

export const selectStr = createSelector(myTopLevelSelector, (state) => {state.str});

Reducer.ts(缩减器.ts)

export const featureKey = 'myFeatureKey';

export interface State {
    str: string,
    numChanged: number
}

export const initialState: State = {
    str: "initialState",
    numChanged: 0
}

const myReducer = createReducer(
    initialState,
    on(myAction1, (state, action) => ({
        ...state,
        str: action.str,
        numChanged: state.numChanged + 1
    }))
)    

export function reducer(state: State | undefined, action: Action) {
    return myReducer(state, action);
}

操作.ts

export const myAction1 = createAction('ACTION1', props<{str: string, numChanged: number}>());

export const myActionSuccess = createAction('ACTIONSUCCESS');

HTML 文件是一个不起眼的单行代码:<p>{{this.str}}</p>

我查看了这个线程(以及它包含的链接):无法在订阅函数中获取组件的“this”,并且问题在格式上有些相似,但根本区别在于我没有尝试记录;我正在尝试分配,但在日志记录工作时分配不起作用。

Angular TypeScript 可观察

评论


答:

1赞 Diego Bascans 4/4/2023 #1

我认为您遇到的问题出在您的选择器中。

从箭头功能中删除括号,如果您有它们,则需要将括号添加到其中。return

不带括号

export const selectStr = createSelector(myTopLevelSelector, (state) => state.str);

带支架

export const selectStr = createSelector(myTopLevelSelector, (state) => { return state.str })

希望对你有所帮助!

评论

1赞 user21559858 4/4/2023
了不起。它就像一个魅力。谢谢。有时我在想,我自己怎么能弄清楚这一点。我想这是关于在这段旅程中走更多的路。