Angular2-Get TypeScript - 对象映射

时间:2017-01-11 18:34:55

标签: angular typescript

我目前正在学习Angular2和Typescript。 我对大多数基本模式都有很好的了解,但我得到的一件事是在observable上实际使用泛型类型以及如何完成映射。也许我可以展示我的榜样: 在服务器端,我有一个Controller返回一些HelloWorld-Objects。这个模型有三个简单的属性,方法如下:

    [HttpGet("helloWorlds")]
    public IEnumerable<HelloWorld> HelloWorlds()
    {
        return new[]
        {
            new HelloWorld
            {
                GreetedPersons = 1,
                GreetingsDate = DateTime.Now,
                GreetingsMessage = "Greetings, traveller"
            },
            new HelloWorld
            {
                GreetedPersons = 1000,
                GreetingsDate = new DateTime(1986, 12, 29),
                GreetingsMessage = "Happy birthday"
            },
            new HelloWorld
            {
                GreetedPersons = 33333,
                GreetingsDate = new DateTime(2017, 01, 01),
                GreetingsMessage = "Happy new year"
            }
        };
    }

我在Tyepscript上有相同的模型,但有驼峰套管:

export class HelloWorld {
public greetingsMessage: string;

public greetingsDate: Date;

public greetedPersons: number;
}

为了抽象HTTP-Requests,我在Typescript上创建了一个通用的Http-Service:

@Injectable()
export class HttpService {
constructor(private http: Http) { }

public get<T>(url: string): Promise<T> {
    return this.processResponse(this.http.get(url));
}

public post<T>(url: string, body: any, contentType: http.ContentType): Promise<T> {
    let headers = new Headers();
    headers.append('Content-Type', this.mapContentType(contentType));

    var requestoptions = new RequestOptions({
        headers: headers
    });

    return this.processResponse(this.http.post(url, body, requestoptions));
}

private processResponse<T>(response: Observable<Response>): Promise<T> {
    return response.map(this.extractJson)
        .toPromise()
        .catch(this.handleError);
}

private mapContentType(contentType: http.ContentType) : string {
    switch (contentType) {
        case http.ContentType.ApplicationJson:
            return "application/json";
        default:
            throw new RangeError(contentType.toString() + " is not recognized");
    }
}

private extractJson(res: Response) {
    const body = res.json();
    debugger;
    return body;
}

private extractArray(res: Response) {
    const body = res.json();
    return body.data || {};
}

private handleError(error: any) {
    // Low Level technical logging
    // We pass the error via promise to give the client the possibility to show a nice message
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }

    console.error(errMsg);
    return Promise.reject(errMsg);
}
}

最后,我的HelloWorld-Service可以请求HelloWorld:

getHelloWorlds(): Promise<HelloWorld[]> {
    const url = "api/HelloWorld/helloWorlds";
    return this.httpService.get<HelloWorld[]>(url);
}

我没有得到:在JSON中,我已经收到了带驼峰外壳的HelloWorld-Properties,所以一切正常! &#34;嗯,一切正常,为什么他甚至打扰?&#34;好问题,因为目前我想使用本教程实现通用SignalR服务:https://blog.sstorie.com/integrating-angular2-and-signalr-part-1/

它也有效,但是骆驼外壳并没有通过一些魔法来应用,所以这个模型

export class ChannelEvent {
name: string;
channelName: string;
timestamp: Date;
data: any;
json: string;

constructor() {
    this.timestamp = new Date();
}
}

不能工作,我需要将其定义为pascal套装。

我发现了将一个TypeScript映射到另一个TypeScript的可能性,但到目前为止,我所见过的教程都没有对此事做过任何说明。

0 个答案:

没有答案