我刚开始学习TypeScript和Angular 2,我无法理解,我做错了什么;
我有错误:response.getTorrents is not a function
我的对象......看起来像是铸造类型的问题(或误解:)。
以下是我的服务代码:
import {Injectable} from "@angular/core";
import {Headers, Http} from "@angular/http";
import {Torrent} from "./torrent";
import 'rxjs/add/operator/toPromise';
import {Body} from "@angular/http/src/body";
class ListResponse {
private results: Torrent[];
count: number;
next: string;
previous: string;
getTorrents(): Torrent[] {
return this.results
}
static createNew(response: Body): ListResponse {
return Object(response) as ListResponse;
}
}
@Injectable()
export class TorrentService {
private torrentsUrl = 'http://localhost:8000/api/torrents/?download=true';
private headers = new Headers({'Access-Control-Allow-Origin': '*'});
constructor(private http: Http) {}
getList(): Promise<ListResponse> {
return this.http.get(this.torrentsUrl)
.toPromise()
.then(response => {
return ListResponse.createNew(response.json())
})
.catch(this.handleError)
}
private handleError(error: any): Promise<any> {
console.error('An error occured', error);
return Promise.reject(error.message || error);
}
}
一些解释:
如果我只使用return new ListResonse(response.json())
,我会收到编译错误:Supplied parameters do not match any signature of call target.)
这是组件:
import {Component, OnInit} from '@angular/core';
import {TorrentService} from "./torrent.service";
import {Torrent} from "./torrent";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit{
constructor(private torrentService: TorrentService) {}
title = 'Torrents';
private next: string;
private previous: string;
count: number;
torrents: Torrent[];
ngOnInit(): void {
this.torrentService.getList().then(
response => {
this.torrents = response.getTorrents();
}
)
}
}