Search code examples
angularangular2-services

How to take data from webapi using angular2


TestTime.ts:

export class TestTime {
    id: number;
    taskRepositoryID: any;
    timesheetID: any;
    timeCategoryID: any;
    startTime: string;
    endTime: string;
    duration: any;
    comment: string;
}

testTime.service.ts:

import { Injectable } from '@angular/core';
import { TestTime } from './TestTime';
import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

 @Injectable()
export class TestTimeService {
public values: any;
constructor(public _http: HttpClient) { }
private _timeTestURL = 'http://localhost:3186/myData;

getTimes() {
    return this._http.get<TestTime>(this._timeTestURL);
}

public getAll<TestTime>(): Observable<TestTime> {
    return this._http.get<TestTime>(this._timeTestURL);
}
}

testTime.component.ts

import { Component, OnInit } from '@angular/core';
import { TestTime } from './TestTime';
import { TestTimeService } from './testTime.service';



@Component({
selector: 'app-testTime-component',
template: `
 <h1> Test Time </h1>
   <ul>
<li ngFor="let time of times">
 <span> {{time}} </span>
</li>
 </ul>
`
})


 export class TimeTestComponent {

constructor(private _timeServcie: TestTimeService) { }

errorMessage: string;
public times: TestTime[];
public TimeSheetData: string;
ngOnInit() {


    this._timeServcie
        .getAll<TestTime[]>()
        .subscribe((data: TestTime[]) => this.times = data,
        error => (ex) => {
            console.log("error" + ex);
        },
        () => {
            console.log("error error"); 
        });
}

 }

Above you can see my code. I can't figure out why I am not getting the data. After the "Test Time" which is in the template of timeTest.component.ts, there is nothing which means I am not even taken correctly the data, cuz if I was taking it correctly at least there should have been the . from the list items


Solution

  • why are you casting the http.get()methods, what you should do instead is to define the return type of the methods and then you will be able to see error more clearly. try this

    getTimes(): Observable<TestTime> {
        return this._http.get(this._timeTestURL);
    }
    
    public getAll(): Observable<TestTime[]> {
        return this._http.get(this._timeTestURL);
    }
    

    and then your observer in component should be like

    this._timeServcie.getAll().subscribe(
            (data: TestTime[]) => this.times = data,
            error => (ex) => {
                console.log("error" + ex);
            },
            () => {
                console.log("completed"); //THIS ISN'T ERROR
            });