I am attempting to connect a variable in a component to the content retrieved from an observable within a subscribe() function using an anonymous arrow function:
ngOnInit() {
this.strSub = this._store.select(selectStr).subscribe((data) => console.log(data));
//this.strSub = this._store.select(selectStr).subscribe((data) => {this.str = data});
}
The line that is not commented out executes smoothly, whereas the commented-out line raises an error during compilation
Type 'void' is not assignable to type 'string'.
.
In simple terms, assigning this.str = data
seems to cause issues within the program. I suspect that the problem may arise from data
being null at some point during runtime, so I tried implementing a check with if (data) {...}
, but it still failed to compile.
I have observed others bind variables in components using this method (so it should be a valid approach), yet I cannot comprehend why it's not permitted in this case.
Below is the comprehensive code example, consisting of a single component.ts file along with selectors.ts, reducer.ts, and actions.ts:
Component.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)
}
}
Selectors.ts
export const myTopLevelSelector = createFeatureSelector<fromReducer.State>(fromReducer.featureKey);
export const selectStr = createSelector(myTopLevelSelector, (state) => {state.str});
Reducer.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);
}
Actions.ts
export const myAction1 = createAction('ACTION1', props<{str: string, numChanged: number}>());
export const myActionSuccess = createAction('ACTIONSUCCESS');
The HTML file is a straightforward one-liner:
<p>{{this.str}}</p>
I referred to this discussion (and the associated links): cannot get 'this' of component inside subscribe function. Although the issue bears similarities in format, a key distinction is that I'm attempting to assign values rather than simply logging them, wherein the assignment fails while logging works as expected.