问题
I am working on angular 6 project. I am using canDeactivate for my routeGuards and a popup to show route leave message. But the issue is coming at my price-list-guard-service on hover .flatMap(isAllow)=> {
Error: Argument of type '(isAllow: boolean) => boolean' is not assignable to parameter of type '(value: boolean, index: number) => ObservableInput<{}>'..
I wanted to do something like this in price-list-guard.service.ts:
price-list-guard.service.ts
@Injectable()
export class PriceListFormGuard implements CanDeactivate<PriceListFormComponent> {
constructor(private promptService: PromptService) { }
canDeactivate(component: PriceListFormComponent):boolean {
if (component.isDirty) {
this.promptService.showPrompt('Warning', 'Unsaved changes detectect on the current page);
this.promptService.callback.flatMap((isAllow) => {
if (isAllow) {
return true;
} else {
return false;
}
});
}
}
}
prompt-service.ts
@Injectable()
export class PromptService {
title: string;
message: string;
display = 'none';
callback: Subject<boolean>;
constructor() {
this.callback = new Subject<boolean>();
}
showPrompt(title: string, message: string): void {
this.title = title;
this.message = message;
this.display = 'block';
}
close(confirm?: boolean): void {
this.title = null;
this.message = null;
this.display = 'none';
if (confirm != null) {
this.callback.next(confirm);
}
}
回答1:
Your canDeactivate
method return type is Boolean. but the method looks like nothing is return. So try this below method instead of your method
canDeactivate(component: PriceListFormComponent):boolean {
// let retVal: boolean = true;
if (component.isDirty) {
this.promptService.showPrompt('Warning', 'Unsaved changes detectect on the current page);
return this.promptService.callback.flatMap((isAllow) => {
if (isAllow) {
return true;
} else {
return false;
}
});
}
return false;
}
回答2:
You can't return a boolean when using async operations.
Change to this:
canDeactivate(component: PriceListFormComponent):Observable<boolean> { // Return an observable
if (component.isDirty) {
this.promptService.showPrompt('Warning', 'Unsaved changes detectect on the
current page);
return this.promptService.callback.asObservable();
} else {
return of(true);
}
}
来源:https://stackoverflow.com/questions/51554591/type-boolean-is-not-assignable-to-type-observableinput