【发布时间】:2018-04-24 20:28:03
【问题描述】:
情况:
我正在使用 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>
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);
});
问题:
我看到我成功接收到的 json 数据(我可以在 google DevTool => Network => XHR 中看到它们)。但我在 Angular 应用程序中看到的所有内容都是'some text'。我在 DevTool 控制台中看到了ERROR TypeError: Cannot read property '0' of undefined。
问题:
哪里出错了?我错过了什么?
【问题讨论】:
标签: node.js angular xmlhttprequest