Angular(2+):HttpClient,subscribe,xhr

时间:2017-11-11 20:44:57

标签: node.js angular xmlhttprequest

情况:

我正在使用Angular CLI。我试图从服务器端(node.js,express)接收数据。我创建了新组件card-object。我从此页面上的示例中复制了此代码: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>

卡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'];
    });
   }
}

卡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);
});

问题:

我看到我成功收到的json数据(我可以在google DevTool =&gt; Network =&gt; XHR中看到它们)。但我在角度应用中看到的所有内容都是&#39;一些文字&#39; 。我在DevTool控制台中看到ERROR TypeError: Cannot read property '0' of undefined

问题:

哪里出错?我错过了什么?

1 个答案:

答案 0 :(得分:0)

初始化数组,使其在异步调用完成之前具有值:

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

如果结果有数据则绑定:

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