2017-10-13 56 views
0

TestTime.ts采取从数据的WebAPI:如何使用angular2

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

} 

以上你可以看到我的代码。我无法弄清楚为什么我没有收到数据。 在timeTest.component.ts模板中的“测试时间”之后没有任何意思,我甚至没有正确地采集数据,因为如果我正确地采取了它,至少应该有从列表项目

+0

你可以阐述你收到这错误? –

+0

@AliTurabAbbasi,我在代码中标记了它。 testTime.component.ts最后一个console.log我已经添加了//这里, – AngularBeg

+0

这并不意味着有错误。无论是否存在错误,()=> {}部分都会在最后执行。如果出现错误,则console.log(“error”+ ex);将打印 –

回答

0

为什么要投射http.get()方法,你应该做的是定义方法的返回类型,然后你将能够更清楚地看到错误。试试这个

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

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

,然后你在组件观察者应该像

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