The enigma of the Angular2 Object's Undefined nature

Encountering an "object undefined" error when trying to access the object of the Service Component. Interestingly, hard coding the data directly into a JavaScript variable works fine and shows the type as "object Array."

Data.json

[
      {
        "id": 1,
        "name": "Malad",
        "gateway": "10.10.100.1",
        "device": "cisco"
      }, {
        "id": 2,
        "name": "Kandhivali",
        "gateway": "222.30.100.1",
        "device": "Juniper"
      }
]

DataService.ts

import {Injectable} from 'angular2/angular2'
import {Http} from 'angular2/http';

@Injectable()
export class DataService {

  tdata = [
  {
    "id": 1,
    "name": "Malad",
    "gateway": "10.10.100.1",
    "device": "cisco"
  }, {
    "id": 2,
    "name": "Kandhivali",
    "gateway": "222.30.100.1",
    "device": "Juniper"
  }
];

  data;
  constructor(http: Http){
    http.get('Data.json')
    .toRx()
    .map(res => res.json())
    .subscribe(res => this.data= res);
  }

}

DataPage.ts

import {Component, View, CORE_DIRECTIVES} from 'angular2/angular2'
import {DataService} from './DataService'

@Component({
  selector: 'DataPage'
})
@View({
  template: `
{{data | json}}  //Working fine //object Array
<br>
{{data | json}}  //Not working // object Undefined //No data :(
`


directives: [CORE_DIRECTIVES]
})

export class DataPage{
  query;
  tquery;
    constructor( public dataService:DataService){

       this.query = dataService.data; // object Undefined
       this.tquery = dataService.tdata; //object Array

  }
}

Answer №1

The reason for this is because the data is being fetched asynchronously. You cannot expect the service to immediately return the value upon calling it. Instead, you should return an Observable in your service and subscribe to it in your component.

Within your service:

constructor(http: Http){
    this.http = http;
}
myData() {
  return this.http.get('Data.json')
     .toRx()
     .map(res => res.json());
}

In your component:

constructor( public dataService:DataService){

       dataService.myData().subscribe(res => this.query = res);

       this.tquery = dataService.tdata; //object Array
  }

Be sure to update your view as follows:

@View({
    template: `
     {{tquery| json}}
     <br>
     {{query | json}}
    `

For a working example, check out this Plunker link: http://plnkr.co/edit/BeMpYR?p=preview

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

Struggling to incorporate generics into a Typescript method without sacrificing the typing of object keys

Currently, I am working on a method in Typescript that is responsible for extracting allowable property types from an object of a constrained generic type. The scenario involves a type called ParticipantBase which consists of properties like first: string ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...

Issues with toggling the menu on Angular 14 using Bootstrap 4.6

I am struggling with implementing a menu on the header section of my Angular 14 homepage. The menu I added is not opening as expected. Even after trying various working menu samples from the internet, I couldn't get it to work in my project. Here are ...

Creating separate template reference variables for items in an *ngFor loop in Angular can be achieved by using the

I have a question about setting template reference variables for buttons with different attributes when rendering them using *ngFor in Angular. Specifically, I want to set the reference variable as #button1, #button2, and so on for each button, but also ne ...

Upgrading from Angular 2 to 4 causes compilation failure in project

Recently, I upgraded my Angular project from version 2 to version 4. The steps I followed for this upgrade are as follows: 1- Deleted the /node_modules/ folder 2- Executed the following command: npm install @angular/common@latest @angular/compiler@lat ...

Tips on extracting a value from a subscription

I am trying to figure out how to pass a value from a subscribe function to a variable so that I can manipulate it later on. For example: getNumber: number; I need to be able to access and use the variable getNumber in the same .ts file. someMethodT ...

Having trouble resolving the typescript package while integrating with another module

Attempting to develop a basic npm package with TypeScript and bundle it using webpack. When trying to use the package in another module, such as a react application named 'module A.' Within module A, the 'myLibrary' package is installe ...

Implementing Angular 8 with Apache: Configuring htaccess for main domain and subdomain applications

I have encountered a perplexing issue with my 2 Angular applications. Both apps function flawlessly when placed in the root directory of a domain on an Apache webserver (hoster). However, I am now facing a challenge as I attempt to relocate them to: App1 ...

The challenges of dealing with duplicate identifiers caused by nesting npm packages in TypeScript

I am facing an issue with my project structure where I have a node_modules folder at the root level and another one within a subfolder named functions. The directory layout looks like this, ├── functions │   ├── index.js │   ├── ...

Angular: accomplish cascading requests to achieve desired outcomes

While exploring Angular rxjs operators, I came across a scenario where I need to send requests to the server that depend on each other. Currently, I have a modal window open and during the ngOnInit lifecycle hook, multiple requests are being sent, some of ...

What is preventing me from retrieving the data accurately? (Angular)

I'm currently facing an issue with a specific part of the application I'm developing: This is how the component's logic works: export class StockStatusComponent implements OnInit{ articles: Article[] = []; selectedLevel: any; constr ...

Unable to compile TypeScript files using gulp while targeting ES5

After starting my first Angular2 app, I encountered an issue where I couldn't use gulp to compile for es5. Below is the dependencies file: "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/compiler-cli ...

Apologies, but there was an error attempting to differentiate 'nombreyo'. Please note that only arrays and iterables are permitted for this action

Encountering an error while attempting to display a class in the HTML. <li> <ul> <li *ngFor="let refac of refactormodel" > -- word_to_rename: {{refac.word_to_rename}} -- renowned_word: {{refac.renowned_word}} ...

An error has occurred in Angular: No routes were found that match the URL segment 'null'

I've recently developed a simple Angular page that extracts an ID (a guid) from the URL and uses it to make an API call. While I have successfully implemented similar pages in the past without any issues, this particular one is presenting challenges w ...

Testing an Angular2 service that employs RxJs subjects through unit testing

Within my application, I developed an AuthService to manage backend service authorization. Utilizing a BehaviorSubject that updates its subscribers, components are notified of new login states. Below is the simplified code snippet: @Injectable() export cl ...

Utilizing Angular Routing for Lazy Loading Modules Triggers Automatic Redirect

Having an Angular2 app with basic routing, my current configuration is as follows: const routes: Routes = [ { path: 'detail', outlet: 'primary', component: DetailComponent }, { path: 'user', outlet: 'primary&apos ...

Despite my efforts to properly run, my angular component is still not being added to the angular module

After attempting to execute ng generate component elements/ElementsHome, I encountered a successful run; however, the terminal did not display the Updated file path as a hyperlink. Instead, it indicated that the component was not created within the module. ...

What is the method for defining a monkey patched class in a TypeScript declarations file?

Let's say there is a class called X: class X { constructor(); performAction(): void; } Now, we have another class named Y where we want to include an object of class X as a property: class Y { xProperty: X; } How do we go about defining ...

Accepting undefined in rest parameter of typescript

I'm struggling with an exercise involving Function parameters: The maximum function below has the wrong type. To allow undefined in the rest arguments, you need to update the type of the rest parameter. Fortunately, you don't have to change the ...

Tips for simulating a "nested" angular service within a component using jest

I'm looking to create a unit test for an Angular Component using Jest. The component, which is built on Angular version 7.2.0, interacts with a nested service through this.api.manageUser.getUsersStats(). My goal is to verify if this method is being ca ...