Angular 2属性在类型上不存在 [英] Angular 2 Property Does not exist on type

查看:227
本文介绍了Angular 2属性在类型上不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个喜欢的班

export class R {
constructor(
    public id: Number,
    public dte: Date,
    ) { }

}

返回R []的服务就像:`

a service That return R[] the code is like :`

return this.http.get(this.serverLocal).map(this.formatDate);

  formatDate(res: Response) {
    const data = res.json() as R[];
        data.forEach(D => {
        D.dte = new Date(D.dte);
    })
    return data;
}

我遇到2个错误:类型'R'上不存在属性'dte'. 我无济于事地更改了很多代码.如果我对ID进行了一些更改,但对dte日期却没有进行更改,则可以正常工作.我在做什么错了?

I get the 2 errors: property 'dte' does not exist on type 'R'. I changed a lot of code for no avail. It's working if I do some change with ID, but not with dte date. What am I doing wrong?

推荐答案

在回答之前,请先查看 HttpClient (如果您将Angular 5用作json()),则不再需要.默认情况下,http get已经返回json.

Before answering, take a look at HttpClient if you are using Angular 5 as json() is no more needed. An http get already returns a json by default.

如果您的json响应仅包含这两个条目(iddte),则只需执行以下操作:

If your json response has only these two entries (id and dte) you simply have to do the following:

. . .

import { HttpClient } from '@angular/common/http';

/** rxjs **/
import { Observable } from 'rxjs/Observable';

getStuff(someUrl: string): Observable<Array<R>> {
    return this.http.get(someUrl);
}

如果您需要一些错误处理,或者例如,如果请求给出错误,请重试,您应该执行以下操作:

If you need some error handling or, for instance, retry if the request gives error your should do something like:

. . .

import { HttpClient } from '@angular/common/http';

/** rxjs **/
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import {catchError} from 'rxjs/operators/catchError';

getStuff(someUrl: string): Observable<Array<R>> {
    return this.http.get(someUrl)
        .pipe(
            retryWhen(errors =>
                // Do Stuff
            ),
            catchError((error: Error)  => {
                return Observable.throw(error);
            })
        );
}

实际不需要映射数据,但是,如果您想这样做,则应该这样做":

There is no actual need of mapping data, but, if you would like to do it, you should do like":

data.map((dataEntry) => new R(dataEntry))

如果您仍在使用Angular 4.x.x,则应使用:

If you are still using Angular 4.x.x, you should get it going with:

. . .

import { Http } from '@angular/http';

/** rxjs **/
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import {catchError} from 'rxjs/operators/catchError';

getStuff(someUrl: string): Observable<Array<R>> {
    return this.http.get(someUrl)
        .pipe(
            map((response: Response) => response.json()),
            catchError((error: Error)  => {
                return Observable.throw(error);
            })
        );
}

这篇关于Angular 2属性在类型上不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆