Establishing a component variable based on data received from an observable

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.

Answer №1

It appears that the issue you are encountering lies within your selector.

To resolve this, make sure to remove the brackets from the arrow function. If they are present, you will need to insert the return statement inside it.

Here is an example without brackets:

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

And with brackets:

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

I hope this explanation helps you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular is detecting an incorrect value in the mask

Recently, I came across the library found at and decided to create a directive utilizing it. My TypeScript code snippet: initForm() { this.form = this.fb.group({ item_number: [this.service.lpu.item_number, Validators.required], ...

The current value of React.createRef() is perpetually empty

Ever since I started working on this code, I've been encountering a problem that seems to have no solution. Here's what's going on: import React, { Component } from 'react'; export class InfoPaneArrow extends Component<InfoPane ...

Creating a navigational sidebar with dynamic responses using Angular 8

Currently, I am working on creating a responsive sidenav USING ANGULAR WITHOUT MATERIAL DESIGN. My goal is to achieve the same level of responsiveness that can be seen on https://angular.io. Within my project, I have created separate components for the top ...

Iterate through a loop to assign values to an object, then transform it back into an object

My goal is to create a Component with a child that could be any component, so I need to assign the props to this Component. I attempted to do this in a loop because I am unsure about the number of props that should be assigned. //Array of objects that I w ...

Angular feature that enables the use of multiple filter values at once through pipes

Using *ngFor, buttons are dynamically generated to filter by different values. For example, if the key 'location' has values 'west' and 'england', buttons for both 'west' and 'england' will be available for ...

Incorporate an HTML file into a div element in Angular

I'm facing an issue while trying to embed a Hosted HTML page in my angular app. Despite following this guide and making necessary adjustments for Angular 7, the div appears blank. I referred to this article: Angular4 Load external html page in a div ...

Transform JSON object to a class/interface object using Typescript

I am currently working on converting an API response into a TypeScript class or interface. The API is returning a list of objects with various properties, but I only require a few specific properties from the response object. Example of API Response: ...

Tips for minimizing delay after user input with Material UI

Background I'm currently working on a website project that includes a carousel of MUI cards using a unique stack as the underlying component. However, I've encountered an issue where there is a noticeable 4-second delay whenever I try to scroll ...

Angular Service Worker enhancements across various domains

Scenario Our team is currently developing an Angular application that is accessible through multiple domains. Depending on the domain, the app will display different colors and content, but it is essentially the same Angular application. To enhance perfo ...

The parameter 'EventTypes' cannot be assigned to a type of string

I am working on enhancing the functionality of the function provided below by adding types to it, clickEvent(event:Event) { this.event = event } The HTML Code: <a [href]="href" [target]="target" (click)="clickEvent('text')"></ ...

In Typescript, it is not possible to use generics as a function parameter in a

Looking for a solution regarding passing the union of two specific samples of generics to a function. The function in question is as follows: function myCommonFunc<T>({ data, render, }: { data: T; render: (data: T) => number; }) { return ...

In the realm of Typescript Angular, transferring the value of an object's property to another property within the

I'm working with a large TypeScript object and I am hoping to automate certain parts of it to streamline my workflow. myObject = [ { id: 0, price: 100, isBought: false, click: () => this.buyItem(100, 0) } buyItem (it ...

Combining HTTPHandler Observable with another in HTTPInterceptor (Angular 8)

In our Angular 8 project, we have set up our API so that the response includes both a "data" attribute and an "errors" attribute. It's possible for there to be data as well as errors in the response, and we need access to both in the calling component ...

Encountering a TypeError in NextJS: "Uncaught window.fbq is not recognized as a function"

Trying to implement Facebook Pixel for event tracking on the client side within my NextJS app-router project. Following the instructions provided in the NextJS pixel repository: https://github.com/vercel/next.js/tree/canary/examples/with-facebook-pixel/ap ...

Angular does not include a particular parameter in the HTTP request

I am currently facing an unusual issue in Angular and Ionic 2 related to a specific provider I have set up. Here is the code snippet: getTransportations = function (category, maxResults) { let url = `${this.domain}/wp-json/gf/v2/forms/1/entries? ...

Looking to create a dynamic Angular reactive form using API response data? Seeking guidance on how to achieve this? Let's

[ { "name": "jkjk", "firstName": "hgh", "lastName": "ehtrh", "replytype": "svdv", "prodCode": "svv", "execu ...

Checking for the existence of a value in an object using Angular loops

I am seeking assistance in verifying the presence of a specific value within an object. My Object = (vagas.etapas) "Etapas" : { "05daf060-87cb-47cf-8c98-65b36941613d" : "Name 1", "0bf7aabf-42df-4f7d-86dc-af81e6cef394 ...

React Native Typescript: Issue with non-existent property

After dabbling in TypeScript for React Native, I've encountered some rather strange error messages that have me stumped. While experimenting with my code, I came across this line: <Text text={user?.last_name} style={{color:colors.textSecondary}} v ...

Error in integrating ng2-bootstrap pagination with a bootstrap table

I am currently working on incorporating the ng2-bootstrap pagination component with a bootstrap table. The bootstrap table I have is populated using the ngFor directive: <tr> <th *ngFor="#col of cols">{{col.header}} </tr> </thead ...

What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to a ...