canActivate 和 NGXS 选择器
canActivate and NGXS selector
我在 SomeService 中有 NGXS 选择器
@Select(state => state.sample)
public sample$: Observable<Sample>;
我在这样的 Angular RouteGuard 中使用它
getSample(): boolean {
this.someService.sample$.subscribe({
next: (sample: Sample) => {
if (isValid(sample)) {
return true;
} else {
return false;
}
},
error: () => {
return false;
}
});
}
canActivate(): boolean {
return this.getSample();
}
我收到一条错误消息“声明类型既不是 'void' 也不是 'any' 的函数必须 return 一个值”。
我知道原因是因为它没有 return 订阅之外的任何东西,但我只想 return 执行订阅后才想 return。
你应该这样做:
// You cannot return the value the way you were trying to do.
// The following snippet shows the right way to do it.
// Notice we're returning an observable instead of a boolean.
// And we are making sure that the observable completes after
// the first emission, by using the `take(1)` operator
getSample(): Observable<boolean> {
return this.someService.sample$.pipe(
// Convert the sample to true or false according to isValid
map((sample: Sample) => isValid(sample)),
// The observable must complete for canActivate get into action
take(1)
}
}
// Can activate can return an Observable<boolean> as long
// as it completes.
canActivate(): Observable<boolean> {
return this.getSample();
}
我在 SomeService 中有 NGXS 选择器
@Select(state => state.sample)
public sample$: Observable<Sample>;
我在这样的 Angular RouteGuard 中使用它
getSample(): boolean {
this.someService.sample$.subscribe({
next: (sample: Sample) => {
if (isValid(sample)) {
return true;
} else {
return false;
}
},
error: () => {
return false;
}
});
}
canActivate(): boolean {
return this.getSample();
}
我收到一条错误消息“声明类型既不是 'void' 也不是 'any' 的函数必须 return 一个值”。 我知道原因是因为它没有 return 订阅之外的任何东西,但我只想 return 执行订阅后才想 return。
你应该这样做:
// You cannot return the value the way you were trying to do.
// The following snippet shows the right way to do it.
// Notice we're returning an observable instead of a boolean.
// And we are making sure that the observable completes after
// the first emission, by using the `take(1)` operator
getSample(): Observable<boolean> {
return this.someService.sample$.pipe(
// Convert the sample to true or false according to isValid
map((sample: Sample) => isValid(sample)),
// The observable must complete for canActivate get into action
take(1)
}
}
// Can activate can return an Observable<boolean> as long
// as it completes.
canActivate(): Observable<boolean> {
return this.getSample();
}