Angular的新手,我在控制台中可以使用JSON。所以后端/ REST调用正常运行。但是我很难理解如何在组件的视图中显示JSON。
import { Component } from 'angular2/core';
import { TradeshowComponent } from './tradeshow/tradeshow.component';
@Component({
selector: 'app-container'
})
export class AppComponent {
constructor() { }
}
import { Component, View } from 'angular2/core';
import { CORE_DIRECTIVES, NgIf, NgFor } from 'angular2/common';
import { DataService } from '../shared/services/data.service';
import { DashboardLayoutComponent } from '../dashboard_layout/dashboard_layout.component';
import { HTTP_PROVIDERS } from 'angular2/http';
@Component({
selector: 'tradeshow',
providers: [DataService, HTTP_PROVIDERS]
})
@View({
templateUrl: 'src/app/tradeshow/tradeshow.component.html',
directives: [DashboardLayoutComponent, NgIf, NgFor]
})
export class TradeshowComponent {
constructor(private _dataService: DataService) { this.getTradeShows() }
getTradeShows() {
this._dataService.getTradeShows()
.subscribe(
tradeshows => this.tradeShows = tradeshows
error => console.error('Error: ' + err)
);
}
}
我正在使用的HTML是:
<div *ngFor="#tradeshows of tradeshows">{{ tradeshows.name }}</div>
我的服务看起来像这样:
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Config} from '../../config/config';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class DataService {
// API path
baseUrl: string = '/api';
authUrl: string;
apiUrl: string;
registerUrl: string;
constructor(private _http: Http, private _config: Config) {
this.apiUrl = this._config.get('apiUrl') + this.baseUrl;
this.authUrl = this._config.get('apiUrl') + '/auth';
this.registerUrl = this._config.get('apiUrl') + '/register';
}
getTradeShows() {
return this._http.get(this.getApiUrl('/tradeshow/list'))
.map((res: Response) => res.json())
.catch(this.handleError);
}
}
答案 0 :(得分:1)
这看起来像个错误
getTradeShows() {
this._dataService.getTradeShows()
.subscribe(
tradeshows => this.getTradeShows() = tradeshows,
error => console.error('Error: ' + err)
);
}
应该是
getTradeShows() {
this._dataService.getTradeShows()
.subscribe(
tradeshows => this.tradeshows = tradeshows
error => console.error('Error: ' + err)
);
}
您可以从
中删除NgIf, NgFor
directives: [DashboardLayoutComponent, NgIf, NgFor]
这些现在全球可用。
更改
<div *ngFor="#tradeshows of tradeshows">{{ tradeshows.name }}</div>
到
<div *ngFor="#tradeshow of tradeshows">{{ tradeshow.name }}</div>
@Child()
前一段时间被删除了
})
@View({
应替换为,
我在这一行中犯了错误
tradeshows => this.tradeShows = tradeshows
应为(小写S)
tradeshows => this.tradeshows = tradeshows