Angularjs 2 TypeError:无法使用Http客户端

时间:2016-03-31 15:05:08

标签: javascript angularjs json rest typescript

自从现在好一周以来,我一直在开发一个angularjs应用程序。我正在为我的服务构建一个后台应用程序。

我无法使用从远程服务器获取的数据。我在我的应用程序中有4个http GET请求,其中2个是获取用户和订单列表,那些工作正常,但另外2个,获取用户详细信息和订单详细信息给我同样的错误。

以下是我获取用户详细信息的错误:

Console error when trying to display user details

这是组件(user-details.component.ts):

import {Component}          from 'angular2/core';
import {ROUTER_DIRECTIVES}  from 'angular2/router';
import {HTTP_PROVIDERS}     from 'angular2/http';

import {UserDetailsModel}   from '../model/user-details.model';
import {UserDetailsService} from '../service/user-details.service';
import {Configuration}      from '../app.constants';

@Component({
    selector: 'user-details',
    templateUrl: 'app/template/user-details.component.html',
    directives: [ROUTER_DIRECTIVES],
    providers: [UserDetailsService, HTTP_PROVIDERS, Configuration]
})

export class UserDetailsComponent {

    errorMessage: string;
    userDetailsModel: UserDetailsModel[];

    constructor (private _userDetailsService: UserDetailsService) { }

    ngOnInit() {
        this.getUserDetails();
    }

    getUserDetails() {
        this._userDetailsService.getUserDetails()
                          .subscribe(
                            userDetailsModel => this.userDetailsModel = userDetailsModel,
                            error => this.errorMessage = <any>error);
    }

}

这是服务(user-details.service.ts):

import {Injectable}         from 'angular2/core';
import {Http, Response}     from 'angular2/http';
import {Observable}         from 'rxjs/Observable';

import {UserDetailsModel}  from '../model/user-details.model';
import {Configuration}      from '../app.constants';

@Injectable()
export class UserDetailsService {

    constructor (private _http: Http, private _config: Configuration) {

        this._actionUrl = _config.serverUrl + 'users/40';

    }
    private _actionUrl: string;


    getUserDetails () {
        return this._http.get(this._actionUrl)
                         .map(res => <UserDetailsModel[]> res.json().user)
                         .do(user => console.log(user))
                         .catch(this.handleError);
    }

    private handleError (error: Response) {
        // in a real world app, we may send the error to some remote logging infrastructure
        // instead of just logging it to the console
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

这是模型(user-details.model.ts):

export class Address {
    constructor (
        public type:                string,
        public address:             string,
        public additional_info:     string,
        public zip_code:            string,
        public city:                string,
        public floor:               number,
        public elevator:            boolean
    ) { }
}

export class Infos {
    constructor (
        public username:    string,
        public email:       string,
        public first_name:  string,
        public last_name:   string,
        public birth_date:  string,
        public gender:      string,
        public telephone:   string
    ) { }
}

export class UserDetailsModel {
  constructor(
    public infos:    Infos[],
    public adresses: Address[]
  ) {  }
}

以下是模板的一部分,我使用服务器中的数据提取(user-details.template.ts):

<div class="row">
    <div class="col-lg-3">
        <img class="img-thumbail" src="http://placehold.it/150x150">
        <p>Rating xxxx</p>
    </div>
    <div class="col-lg-3">
        <p>Nom : {{userDetailsModel.infos[0].last_name}}</p>
        <p>Prénom : {{userDetailsModel.infos[0].first_name}}</p>
        <p>Date de naissance : {{userDetailsModel.infos[0].birth_date}}</p>
        <p>Adresse : {{userDetailsModel.adresses[0].address}}</p>
        <p>Code postal : {{userDetailsModel.adresses[0].zip_code}}</p>
        <p>Villee : {{userDetailsModel.adresses[0].city}}</p>
    </div>
    <div class="col-lg-3">
        <p>E-mail : {{userDetailsModel.infos[0].email}}</p>
        <p>Téléphone : {{userDetailsModel.infos[0].telephone}}</p>
        <p>Note moyenne </p>
        <p>Courtoisie</p>
        <p>Donne un coup de main</p>
    </div>
</div>

最后,这是我从API调用得到的json响应:

{
  "detail": "success"
  "user": {
    "infos": [1]
     0:  {
     "username": "john.doe@domain.com"
     "email": "john.doe@domain.com"
     "first_name": "Johan"
     "last_name": "Doe"
     "birth_date": "1994-07-09T05:00:00.000Z"
     "gender": "M"
     "telephone": "0612365478"
  }-
-
  "adresses": [1]
    0:  {
     "type": "Principal"
     "address": "2 place du chateau"
     "additional_info": null
     "zip_code": "35500"
     "city": "VITRE"
     "floor": null
     "elevator": null
    }-
  -
  }-
}

先谢谢你一起来看看,我希望你能帮我找到我做错的事。

修改 我在主包装模板中添加了一个指令“* ngIf =”userDetailsModel“,现在它工作正常。事实上,模板运行并尝试在检索数据的实际http请求完成之前访问对象属性。

1 个答案:

答案 0 :(得分:0)

您似乎将userDetailsModel定义为UserDetails数组:

userDetailsModel: UserDetailsModel[];

如果是这种情况,则需要在使用时指定索引。

userDetailsModel[x].propertyName

否则将其声明为UserDetailsModel的实例:

userDetailsModel: UserDetaislModel