首页 文章

如何使用Angular2中的observable更新类

提问于
浏览
0

我的问题很简单 . 我有一个学习班 . 我想(当我点击一个按钮时)将这个课程改为另一个学习 . 所以我创建了一个observable,它给了我这个类(通过.json) . 但是当我订阅这个observable时,通过我的函数'getStudy',我的课堂学习发生了变化,但不会出现{} .

我的学习 . 组件

import {StudiesListService} from '../_services/studieslist.service';
import {studiesList} from '../_models/studiesList';
import {Observable} from 'rxjs/Rx';
import {HttpModule} from '@angular/http';
import {Study} from '../_models/study';
import {StudyProvider} from '../_services/studyprovider.service';
@Component({
  moduleId: module.id,
  selector: 'studiescomponent',
  templateUrl: 'studies.component.html',
})


export class StudiesComponent {
  studyName : string = "test"
  public study : Study = { name: 'test'} ;
  studieslist : studiesList;

  constructor(private _studiesListService : StudiesListService,
              private _studyProvider : StudyProvider ){
  }

 ngOnInit(){
    this._studiesListService.getStudiesListfromAPI()
                            .subscribe( res => this.studieslist =res,
                                        err => console.error(err.status)
     );
}

getStudy(studyName : string){
    this._studyProvider.getStudyfromAPI(studyName)
     .subscribe( res => this.study=res,
                 err => console.error(err.status));

  }
}

请注意,StudiesListService为我提供了研究列表 .

这是我的studyProvider.service

import {Injectable} from '@angular/core';
import {Http} from '@angular/http'
import {Study} from '../_models/study'
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do'
@Injectable()

export class StudyProvider{
  public data : Object;
  constructor(private _http:Http){

 }
  getStudyfromAPI(studyname : string){
    var path : string = '../CDN/';
    path = path.concat(studyname);
    path = path.concat('.json');
    return this._http.get(path)
      .do( x => console.log(x))
      .map( res =>res.json())
  }
}

1 回答

  • 0

    getStudyfromApi方法返回一个数组 . 所以我只需要在study.component中更改它

    this._studyProvider.getStudyfromAPI(studyName)
         .subscribe( res => this.study=res,
                     err => console.error(err.status));
    

    通过

    this._studyProvider.getStudyfromAPI(studyName)
         .subscribe( res => this.study=res[0],
                     err => console.error(err.status));
    

    一切正常,感谢@AhmedMusallam的回答

相关问题