Angular 2+和服务中的服务

时间:2018-01-05 13:27:41

标签: angular

我想在另一个服务中使用一个服务。我想从parametrs-results.service中的private-lessons.service调用getPrivateLessons,但它不起作用,它返回“undefined”。另外,我在模块中提供了这两种服务。如何解决?

私有lessons.service

@Injectable()
export class PrivateLessonsService {

  private _privateLessonsUrl: string = "http://localhost:3000/api/lessons";

  constructor(private _http: Http) {}

  getPrivateLessons() {
    return this._http.get(this._privateLessonsUrl)
      .map( (response: Response) => response.json() );    
  }
}

parametrs-results.service

@Injectable()
export class ParametrsResultsService {

  privateLessons: PrivateLesson[];

  constructor(private _privateLessonsService: PrivateLessonsService) { 
    this._privateLessonsService
      .getPrivateLessons()
      .subscribe(responseData => this.privateLessons = responseData);
  }


  getPrivateLessons() {
    return this.privateLessons;
  }

}

编辑:

当我使用

 this._privateLessonsService
  .getPrivateLessons()
  .subscribe(responseData => {

  this.privateLessons = responseData;
  console.log('this.privateLessons', this.privateLessons);

});

...它正确地显示了privateLessons。当我想在组件中使用getPrivateLessons时,我得到'undefined'。我需要这些数据用于我服务中的进一步操作。如何解决?

1 个答案:

答案 0 :(得分:0)

就像我在上面的评论中所说的那样,我不确定你通过其他服务改变电话的动机是什么,但是如果你需要这样做,试试这个:

@Injectable()
export class ParametrsResultsService {

    constructor(private _privateLessonsService: PrivateLessonsService) { 
    }


    getPrivateLessons() {
        return this._privateLessonsService
        .getPrivateLessons();
    }

}
相关问题