我正在开发一个Angular4应用程序,我想访问我请求抛出2个服务的组件中的数据 . 当我在这种状态下执行代码时,组件内的service-call不会返回任何数据 . 当我尝试使用console.log时,我的服务调用的行根本没有被执行 .
所以我的问题是,为什么我从服务功能中得不到返回值?
我测试了服务,它从我的GET-Request接收数据 .
有人可以帮助我将我的数据放入组件内的本地变量中,并向我解释它是如何工作的吗?
我对角度很新,并且对如何改进我的代码有任何建议 .
提前致谢 .
我想要访问数据的组件
export class ComponentA implements OnInit {
public skills: Skill[];
ngOnInit() {
this.getColleagueSkills(3);
}
getColleagueSkills(colleague_id: number) {
console.log('function');
debugger;
this.skills = this.skillService.getSkillsForColleague(colleague_id);
console.log('after function');
}
}
我调用的第一个服务来获取数据
@Injectable()
export class SkillsService {
private SkillUrl = ...;
private RatingUrl = ...;
constructor(private http: Http, private colleagueService: ColleagueService) {
}
getSkillsForColleague(colleague_id: number) : Skill[]{
let ratedSkillsForColleague = [];
let colleagueRating = [];
let colleague: Colleague;
this.colleagueService.getColleague(colleague_id).subscribe(
data => { colleague = data},
error => {},
() => {
colleagueRating = colleague.coll_rating;
for ( let r in colleagueRating){
ratedSkillsForColleague[r] = colleagueRating[r].rating_skill;
}
return ratedSkillsForColleague;
}
)
return ratedSkillsForColleague;
}
我在服务中调用的服务
@Injectable()
export class ColleagueService {
private ColleagueUrl = ...;
constructor(private http: Http) { }
getColleague(id: number){
const url = `${this.ColleagueUrl}${id}`
return this.http.get(url).map(
response => response.json()).catch(this.handleError);
}
1 回答
这个功能:
...返回并清空数组,因为在给
getColleague
有机会返回数据之前,你立即返回ratedSkillsForColleague
.最好让
getSkillsForColleague
返回一个Observable或Subject,然后订阅它以返回您的数据 .