Search code examples
node.jsangularxmlhttprequest

Angular (2+): HttpClient, subscribe, xhr


Situation:

I'm using Angular CLI. And I'm trying to receive data from the server side (node.js, express). I created new component card-object. I copied this code from the example on this page: https://angular.io/guide/http

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
import { MatGridListModule, MatCardModule } from '@angular/material';


import { AppComponent } from './app.component';
import { CardObjectComponent } from './card-object/card-object.component';


@NgModule({
  declarations: [
    AppComponent,
    CardObjectComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    MatGridListModule,
    MatCardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html:

<app-card-object></app-card-object>

card-object.component.ts:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-card-object',
  templateUrl: './card-object.component.html',
  styleUrls: ['./card-object.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class CardObjectComponent implements OnInit {
  results: string[];

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('http://localhost:3000/?cll=bjc').subscribe(data => {
      this.results = data['results'];
    });
   }
}

card-object.component.html:

<p>{{results[0]}}</p>
<p>some text</p>

node.js:

app.get('/', (req, res) => {
    var reqCard = {
        results: ['text 1', 'text 2']
    };
    res.json(reqCard);
});

Problem:

I see that json data I receive successfully (I can see them in google DevTool => Network => XHR). But everything that I see in my angular app is 'some text'. And I see ERROR TypeError: Cannot read property '0' of undefined in my DevTool console.

Question:

Where is a mistake? What have I missed?


Solution

  • Initialize your array so that it has a value before the async call completes:

      ngOnInit(): void {
        this.results = []
        this.http.get('http://localhost:3000/?cll=bjc').subscribe(data => {
          this.results = data['results'];
        });
       }
    

    Bind if results has data:

    <p>{{results.length > 0 ? results[0]: ''}}</p>
    <p>some text</p>