0

I've just started learning TypeScript and Angular 2 and I can't understand, what I'm doing wrong;

I've got error: response.getTorrents is not a function of my object... Looks like it's problem (or misunderstanding :) ) of types casting.

Here is code of my service:

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

Some explanations: If I just use return new ListResonse(response.json()), I get compile error: Supplied parameters do not match any signature of call target.)

Here's the component:

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();
      }
    )
  }
}
antonio_antuan
  • 1,293
  • 9
  • 22

0 Answers0