如何使用angular2

时间:2017-10-13 11:56:00

标签: angular angular2-services

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

 }

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

中获取

1 个答案:

答案 0 :(得分: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
        });