我正在开发一个Angular4应用程序,我想访问我请求扔掉2个服务的组件中的数据。 当我在此状态下执行代码时,组件内的service-call不会返回任何数据。当我尝试使用console.log时,我的service-call的值根本没有被执行。
所以我的问题是,为什么我不能从我的服务功能中获得返回值?
我测试了该服务,它从我的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);
}
答案 0 :(得分:1)
这个功能:
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;
}
...返回并清空数组,因为在您ratedSkillsForColleague
有机会返回数据之前,您会立即返回getColleague
。
最好让getSkillsForColleague
返回一个Observable或Subject,然后订阅它以返回您的数据。
getSkillsForColleague(colleague_id: number) : Subject{
let subject = new Subject();
let ratedSkillsForColleague = [];
let colleagueRating = [];
let colleague: Colleague;
this.colleagueService.getColleague(colleague_id).subscribe(
data => { mitarbeiter = data},
error => {},
() => {
colleagueRating = colleague.coll_rating;
for ( let r in colleagueRating){
ratedSkillsForColleague[r] = colleagueRating[r].rating_skill;
}
subject.next(ratedSkillsForColleague);
}
)
return subject;
}