rxjs与HttpClient一起使用时的困惑

时间:2018-08-04 23:10:43

标签: typescript rxjs angular-httpclient

我正在尝试使用http.get的键入版本。如何获取要添加到this.rowData的类型化数组? 以下的c参数是数组本身:

this.rowData = this.courseProvider.getCourses().map(c => new Course(c));

// course.provider.ts

import 'rxjs/add/operator/share';
import 'rxjs/add/operator/mergeMap';
import { Injectable } from '@angular/core';
import { Api } from '../api/api';
import { Course } from '../../models'

@Injectable()
export class CourseProvider 
{
    course: Course;

    constructor(public api: Api)
    {
    }

    getCourses()    {
        let observable = this.api.get<Course[]>('courses');

        observable.subscribe((courses: Course[]) => {
        }, err => {
            console.error('ERROR', err);

            throw err;
        });

        return observable;
    }
}

// course.ts

export class CoursePage extends GridPageBase {

    ngOnInit() {
        this.rowData = this.courseProvider.getCourses().map(c => new Course(c));
    }
}

// api.ts

import { HttpClient, HttpParams, HttpHeaders, HttpEvent } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class Api {
    url: string = 'http://192.168.0.2:39049/Services/api';

    get<T>(endpoint: string, params?: any, reqOpts?: any) : Observable<T> {

        if (!reqOpts) 
        {
            reqOpts = this.getHeaders();
        }

        return this.http.get<T>(this.url + '/' + endpoint, {
            headers: reqOpts
        });
    }
}

0 个答案:

没有答案