angular - Angular - 定義typeScript時出錯promise如何修復?

我試圖在angualr程序中建立登錄授權來保護一些路由,但是在auth-guard.service中,編譯時得到一個TS錯誤,以下是auth-guard.service的代碼:


 import { CanActivate,


 ActivatedRoute,


 RouterStateSnapshot,


 ActivatedRouteSnapshot,


 Router


 } from '@angular/router';


import { Observable } from 'rxjs/Observable';


import { Injectable } from '@angular/core';



import { AuthService } from './auth.service';



@Injectable()


export class AuthGuard implements CanActivate {


 constructor(private authService: AuthService, private router: Router ) {}



 canActivate(route: ActivatedRouteSnapshot,


 state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {


 return this.authService.isAuthenticated()


 .then(


 (authenticated: boolean) => {


 if (authenticated) {


 return true;


 } else {


 this.router.navigate(['/']);


 return false;


 }


 }


 );



 }


}



我得到的錯誤如下:


ERROR in src/app/auth-guard.service.ts(19,26): error TS2339: Property 'then' does not exist on type 'void'.



這是auth-service.ts:


export class AuthService {


 loggedIn = false;



 isAuthenticated() {


 const promise = new Promise (


 (resolve, reject) => {


 setTimeout(() => {


 resolve(this.loggedIn);


 }, 800);


 }


 );


 }



 login() {


 this.loggedIn = true;


 }



 logout() {


 this.loggedIn = false;


 }


}



isAuthenticated是否需要定義返回值?我做錯什麼了?

謝謝。

时间: 原作者:

你需要返回Promise:


isAuthenticated() {


 return new Promise ((resolve, reject) => {


 setTimeout(() => {


 resolve(this.loggedIn);


 }, 800);


 });


}



你也可以像這樣定義它的返回類型:


isAuthenticated(): Promise<boolean> {


 ...


}



原作者:

需要在isAuthenticated方法中返回promise。


isAuthenticated() {


 const promise = new Promise (


 (resolve, reject) => {


 setTimeout(() => {


 resolve(this.loggedIn);


 }, 800);


 }


 );


 return promise;


}



原作者:

或者,你可以讓方法async返回Promise,並且不需要所有返回new Promise(),


async isAuthenticated() {


 new Promise (


 (resolve, reject) => {


 setTimeout(() => {


 resolve(this.loggedIn);


 }, 800);


 }


 );


 }



有時使wait helper函數更具可讀性:


async isAuthenticated() {


 await wait(800);


 resolve(this.loggedIn);


 }



async wait(ms: number) {


 return new Promise((resolve) => {


 setTimeout(() => resolve(), ms);


 });


}




原作者:
...