我是新手angular2。我正在建立一个网站来开始玩这个平台。问题是当我查询API消息时无法正确转换对象。虽然我认为承诺存在问题。
代码组件如下:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from '../Service/Authentication.service';
import { NoticiesService } from '../Service/Noticies.service';
import { Logger } from '../Service/Logger.service';
import { Noticia } from '../Model/Noticia';
@Component({
selector: 'my-home',
templateUrl: 'app/View/html/Home.component.html',
styleUrls: ['app/Content/css/app.component.css'],
})
export class HomeComponent {
llistaNoticies: Noticia[];
missNoticies = 'Noticies Actuals:';
authenticatedUser = localStorage.getItem('usuari');
sessionUp = this._serviceAuthentication.isSession;
constructor(
private _logger: Logger,
private _serviceAuthentication: AuthenticationService,
private _noticiesService: NoticiesService) { }
getNoticies(): void {
this._noticiesService.getNoticies()
.then(noticies => this.llistaNoticies = noticies);
console.log('getNoticies() passat!')
}
ngOnInit(): void {
this.getNoticies()
console.log('ngOnInit() passat!')
}
logOut() {
this._serviceAuthentication.logOut();
}
}
服务守则是:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Http, Response,
Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Noticia } from '../Model/Noticia';
@Injectable()
export class NoticiesService {
private URLNoticies = 'http://localhost:50541/api/Noticies';
constructor(
private _router: Router,
private _http: Http) { }
getNoticies(): Promise<Noticia[]> {
return this._http.get(this.URLNoticies)
.toPromise()
.then(response => response.json().data as Noticia[])
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
HTML代码的组成部分:
<div class="block-general m-t-1 subTitolPag">
<h2 class="titolPag">Notícies d'actualitat:</h2>
</div>
<div class="row p-a-1">
<div id="block-central" class="block-sub col-md-6 offset-md-2">
<div *ngFor="let noticia of llistaNoticies">
<hr />
<div class="card">
<img class="card-img-top imgNoticia" src="{{noticia.PathImatge}}" alt="Card image cap" style="max-width: 100%;">
<div class="card-block">
<h4 class="card-title titolNoticia">{{noticia.Titol}}</h4>
<p class="card-text">{{noticia.Cos}}</p>
<div class="clearfix">
<h5 class="pull-xs-right">Autor: <span class="label label-default pull-xs-right">{{noticia.Autor}}</span></h5>
</div>
<div>
<h6 class="pull-xs-right">Data de: {{noticia.Data}}</h6>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3 block-sub m-x-1 p-a-1">
<p>Usuari registrat: <span class="text-uppercase">{{authenticatedUser}}</span></p>
<div class="clearfix m-t-1">
<button type="submit" class="btn btn-primary pull-xs-right" (click)="logOut()">Desconecta</button>
</div>
</div>
</div>
上课:
export class Noticia {
public Id: number;
public Titol: string;
public Cos: string;
public Autor: string;
public PathImage: string;
public Data: Date;
}
如果有人发现错误在哪里,并告诉我在哪里可以找到明确的承诺,将非常感激。
谢谢!
答案 0 :(得分:0)
我建议使用Observable
s。
@Injectable()
export class NoticiesService {
private URLNoticies = 'http://localhost:50541/api/Noticies';
constructor(
private _router: Router,
private _http: Http) { }
getNoticies(): Observable<Noticia[]> {
return this._http.get(this.URLNoticies)
.map(response => response.json().data as Noticia[])
.catch(this.handleError);
}
private handleError(error: any): Observable<any> {
console.error('An error occurred', error);
return Observable.of(error.message || error);
}
}
并使用您的服务:
getNoticies(): void {
this._noticiesService.getNoticies()
.subscribe(
noticies => this.llistaNoticies = noticies,
err => console.log(err)
);
console.log('getNoticies() passat!')
}