When you sign up for a Selector subscription, you are met with nothing but

I am facing an issue with a selector that is passing data to a child component. Although the selector is functioning correctly and the child component is being constructed properly, I am encountering problems when trying to subscribe to the selector in the parent component. When I attempt to use the information for a different task, the subscribe function returns an undefined value. Can anyone help me identify where I may be going wrong?

Here is my code snippet:

size: any;
mySubscription: Subscription;

constructor(
    private AppStore: Store<Store.NewState>
  ) { }

  ngOnInit() {
       this.position$ = this.AppStore.select(positionSelectors.selectPositionState);
       if (!this.position$ === undefined) {
         this.mySubscription = this.position$.subscribe((resp) => {
         this.size = Object.keys(resp).length;
        });
        this.mySubscription.unsubscribe();
       }
  }

My goal is to retrieve the length of the response, but it seems nothing is getting past the conditional check. If I remove the condition, I receive multiple errors indicating that the Object is undefined. The specific error I am encountering is:

TypeError: Cannot convert undefined or null to object

Answer №1

The main cause of the issue is,

There is a negation before !this.position$ which results in false, and then you are strictly checking it with undefined, causing it to never enter the if block because it always evaluates as false.

Following a suggestion made in a comment, it is recommended to use the ngOnInit & ngOnDestroy life cycles. Please see the code snippet below for reference:

ngOnInit() {
  this.position$ = this.AppStore.select(positionSelectors.selectPositionState);
  if(!this.position$) this.mySubscription = this.position$.subscribe(() => console.log("Logic Here"));
}

ngOnDestroy() {
  if(this.mySubscription) this.mySubscription.unSubscribe();
}

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

How do you define prop types when passing them in Nextjs?

Welcome to my page import { InferGetServerSidePropsType, GetServerSideProps } from 'next' import ProductList from '../../component/product/ProductList' export interface Item { title: string price: number } const products ...

Transforming the Server-side model to the Client-side model within Angular 4

My Server-side C# model public class Instructor:Entity { public string Name { get; set; } public string PhoneNo { get; set; } } Client-side TypeScript model export class Instructor extends Entity { public name:string; public address ...

Determine the dynamic height of content in a TypeScript file

Could you please provide guidance on obtaining the height of the content within this particular div element? For example, I need to calculate the dynamic height of the content. https://i.sstatic.net/2kNk3.png code .html <div class="margin-top-4 ...

Customizing event typings for OpenTok in Typescript

Currently, I am working on integrating chat functionality using the 'signal' events with the OpenTok API. Here is my event listener that successfully receives the signal: // Listen for signal CHAT_MESSAGE sess.on('signal:CHAT_MESSAGE', ...

Checking the next route in Angular 2 when navigating away

Is there a way to trigger an action only on specific NavigationEnd router events, excluding when navigating between child routes or on a particular route? This is a snippet from my app.routing.ts: // other route configurations... { path: 'scrapers/ ...

Angular 12 route loading component without needing to explicitly declare it in the module registration

Update on Angular Version and CLI Attention: We have a significant change coming up with the next release regarding the CLI npm package. The package will be moved to "@angular/cli" and will only support Node version 6.9 and above. After this transition, t ...

Tips for implementing lazy loading for a section of a template in Angular 2

I have an Angular 2 component that has several sub-components within it. Some of these sub-components are expensive to load and may not always be necessary, especially if the user doesn't scroll far enough down the page. Although I am familiar with l ...

Looking for assistance with transitioning from meteor 1.6.0.1 to 1.6.1 and from angular2-compilers to angular-compilers

Looking to update an Angular/Meteor app from Meteor version 1.6.0.1 to 1.6.1. Recently made the move after addressing a fix at this link. The primary issue encountered is with the old method of importing html files as templates for Angular components: im ...

Ways to display/trigger a dropdown list from the top in Kendo Multiselect module for Angular

On my page, I have implemented a Kendo Multiselect dropdown list. Currently, when clicked, the list expands top to bottom (downwards) but for my specific requirements, I need it to display bottom to top (upwards). I referred to the Kendo UI Angular docume ...

Tips for properly narrowing a function parameter that includes "an object key or a function"

Working on a function to retrieve a property using either a string key or a callback, I've encountered an issue with TypeScript narrowing the type parameter. Here is the function in question: function get<T, V>(value: T, fn: (value: T) => V) ...

Tips for creating a default route with parameters in Angular Component Router?

I am trying to set a default route in my sub-component (using useAsDefault: true) and have parameters automatically passed to it, but I can't seem to find any information on how to accomplish this in the documentation. I have a parent component with t ...

Leverage the most recent API data (fetched with useEffect) to modify a different state variable

My application retrieves movie information from an API as an array through the UseEffect hook and stores it in state (movies). Additionally, I have a function (getIndexMovie) that fetches a random movie object from the movie array and saves it in another s ...

The discovery document is expecting the issuer to be angular-oauth2-oidc in Azure B2C, but the issuer is

During the development of my Angular2 App, I encountered an issue while attempting to implement authentication using a B2C Tenant. Unfortunately, I am receiving the following error: Invalid issuer in discovery document expected: I have followed the setup ...

Using React and TypeScript to pass a custom tag name through props

Using string templates for solutions like this can lead to issues in TypeScript: // var name must start with a capital letter const CustomTag = `h${this.props.level}` as keyof JSX.IntrinsicElements; <CustomTag>Hello</CustomTag> (source1, sour ...

Issues with redirecting to HTTPS on the homepage in Node.js and Express causing problems

I have set up two servers - one for http and the other for https on my VPS using Express: var httpServer = http.createServer(app); httpServer.listen(httpPort); var httpsServer = https.createServer(credentials, app); httpsServer.listen(httpsPort); To red ...

How can I access members outside of a class without a name in Typescript?

I recently developed an "anonymous" class inspired by this insightful discussion on Typescript anonymous classes. However, I'm facing a challenge in accessing the outer scope members. Here's a snippet of my code for context: class BaseCounter { ...

Managing development environments and webpack configuration in Angular CLI 6.0.1

Within the angular.json file, there is a section that looks like this: "configurations": { "production": { "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": ...

Switching the Require statement to an Import statement led to an error popping up

Currently, I am exploring the use of Ajv with typescript. import { Ajv } from "ajv"; let ajv = new Ajv({allErrors: true}); I have encountered an error and I'm unsure why it is occurring: [ts] 'Ajv' only refers to a type, but is being u ...

Parameterized custom validation

I am currently working with Ionic 2 and Angular 2 beta 11. One of my custom validators is functioning perfectly. However, I now find myself in need of adding another custom validation method, but I am struggling to figure out how to pass a parameter to it ...

Creating a subclass or extending a Promise in Typescript does not require referencing a constructor value that is compatible with Promises

I am currently working on a way to terminate my async method call in Typescript. In order to achieve this, I decided to create a new type of Promise that extends from the standard Promise: class CustomPromise<T> extends Promise<T>{ priva ...