如何在angular2中执行http调用

时间:2016-08-20 12:19:08

标签: http angular typescript

我正在尝试获取编辑目的的详细信息,但我不确定如何使用observables可以帮助我的问题是编辑功能。

    @Component({
        selector: 'Search',
         templateUrl:  './components/search/search.html',
       directives: [REACTIVE_FORM_DIRECTIVES],
        providers : [GetSocietyList],

   })

       export class Search {
         property:any = 'Add';
         data: string;
         form:any;
         prop: string = 'connenct';
         details: IStudent1[];
         details1: IStudent2[];

     constructor(fbld: FormBuilder,public http: Http,private _profileservice:GetSocietyList) {
    this.details = [];
    this.http = http;
    this._profileservice.getSocietyList()
        .subscribe(details => this.details = details);
        console.log(this.details);
    this.form = fbld.group({
        name: [''],
        age: ['', Validators.required],
        class: ['', Validators.required],
        grade: ['', Validators.required]

    });

  }

   edit(id): any {
    //console.log(id);
    this.property = 'update';
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded')
    this.http.get('http://localhost/a2server/index.php/profile/editprofiledb/' + id, { headers: headers })
        .subscribe(response => {
            if (response.json().error_code == 0) {
                this.details = <IStudent2[]>response.json().data;

            } else {
                this.details = <IStudent2[]>response.json().data;


        }

  }      )}

我正在尝试获取编辑目的的详细信息,但我不确定如何使用observables可以帮助我的问题是编辑功能。

1 个答案:

答案 0 :(得分:1)

this._profileservice.getSocietyList()
    .subscribe(details => this.details = details);
    console.log(this.details);

这将始终记录undefined,因为您在订阅observable后立即进行了日志记录。您需要等待请求完成以查看数据:

this._profileservice.getSocietyList()
    .subscribe(details => {
      this.details = details;
      console.log(this.details);
    });

因此,您的数据提取最有可能起作用,您只是想过于急切地记录它。