我想在另一个中使用来自订阅方法的值,但是它给了我undefined,因为它不是异步的。有没有一种方法可以将这些值一起使用?我想在下面的订阅方法中再次使用this.internships
,但它变得未定义。谢谢你的帮助!
代码:
ngOnInit(): void {
this._internshipAssignmentService.getInternshipAssignments()
.subscribe(internships => { this.internships = internships; <---- value which gives an object
this.internshipsHelper = internships; console.log(this.internships)},
error => this.msgs.push({
severity: 'error',
summary: 'Error',
detail: 'Er is een onverwachte fout opgetreden.'
}));
this.sub = this._route.params.subscribe(
params => {
let id = +params['id'];
this._internshipAssignmentService.getAllFavorites()
.subscribe(f => {
this.favorites = f;
this.favorite = this.getFavoritesFromIdStudent(1);
console.log(this.internships); <----- value which gives undefined
this.getFavorites(this.favorite);
});
}
);
}
答案 0 :(得分:0)
this.internships
为undefined
,因为这些调用是异步的,您可以获得更多信息here。
另请注意,您使用的是多次订阅,这不是一个好习惯,您应该使用switchMap
map
,pluck
之类的ngOnInit(): void {
this.sub = this._internshipAssignmentService.getInternshipAssignments().do((internships) => {
this.internships = internships; // not needed if you just use it in next callbacks
this.internshipsHelper = internships;
console.log(this.internships)
}).catch(error => {
this.msgs.push({
severity: 'error',
summary: 'Error',
detail: 'Er is een onverwachte fout opgetreden.'
})
}).switchMap(internships => this._route.params.pluck('id').switchMap(id => {
return this._internshipAssignmentService.getAllFavorites().do(f => {
this.favorites = f;
this.favorite = this.getFavoritesFromIdStudent(1);
this.getFavorites(this.favorite);
})
}))
.subscribe();
}
等operators组合您的观察结果。
// going line by line for explanation
public static Integer[] sort(Integer[] array)
{
Arrays.sort(array);//first of all sort the numbers in increasing order
final double median;
/*
now in sorted numbers median is the
--- average of middle two values for even count of numbers; like for 10 numbers median is (4th item +5th item )/2
--- middle value if there are odd count of numbers like for 11 items the median is the 6th item
*/
if (array.length % 2 == 0)
median = ((double)array[array.length/2-1]+ (double)array[array.length/2])/2;
else
median = array [array.length/2];
//now we have the median
// here we have a Comparator for comparing any value during with the median value
Comparator<Integer> compareToMedian= new Comparator<Integer>()
{
@Override
public int compare(Integer o1, Integer o2)
{
// first we check the distance of two numbers from the median; that is the difference from the median
double value = Math.abs(o1 - median) - Math.abs(o2 - median);
if (value == 0)//if the difference is same then we compare the numbers
value = o1 - o2;
return (int)value;//otherwise we return the difference
}
};
Arrays.sort(array, compareToMedian);//sort the numbers with respect to median
return array;
}