Type 'boolean' is not assignable to type 'ObservableInput<{}>'

余生长醉 提交于 2020-01-15 04:40:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!