简体   繁体   中英

How to perform http call in angular2

I am trying to get the details for edit purpose but i am not sure how to do it with observables can some one help me the issue is with edit function.

    @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;


        }

  }      )}

I am trying to get the details for edit purpose but i am not sure how to do it with observables can some one help me the issue is with edit function.

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

this will always log undefined because you're logging right after subscribing to the observable. You need to wait for the request to finish to see the data:

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

So your data fetching most likely works, you're just trying to log it too eagerly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM