输入&#39; Observable&lt; {}&gt;&#39;不能赋予类型&#39; Observable <boolean> |布尔&#39;

时间:2016-07-11 05:04:57

标签: typescript angular

我试图关注this tutorial,但我收到了错误。

  1. pathMatch:&#39; full&#39;。我尝试更改&#34; @ angular / router &#34;到&#34; 3.0.0-beta.2 &#34;,仍然是同一个问题。
  2. 我的依赖项:

    "dependencies": {
        "@angular/common": "2.0.0-rc.3",
        "@angular/compiler": "2.0.0-rc.3",
        "@angular/core": "2.0.0-rc.3",
        "@angular/http": "2.0.0-rc.3",
        "@angular/platform-browser": "2.0.0-rc.3",
        "@angular/platform-browser-dynamic": "2.0.0-rc.3",
        "@angular/platform-server": "2.0.0-rc.3",
        "@angular/router": "3.0.0-beta.2",
        "@angular/router-deprecated": "2.0.0-rc.2",
        "nativescript-angular": "0.2.0",
        "tns-core-modules": "^2.1.0"
    },
    
    1. 输入&#39; Observable&lt; {}&gt;&#39;不能分配给&#39; Observable &#39;,它指向&#39;返回o&#39; ;

      canDeactivate(): Observable<boolean> | boolean {
      
      if (!this.crisis || this.crisis.name === this.editName) {
      
      return true;
      }
      let p = this.dialogService.confirm('Discard changes?');
      let o = Observable.fromPromise(p);
      return o;
      }
      
    2. 有人可以指导我修复这些错误吗?感谢。

3 个答案:

答案 0 :(得分:4)

你可以尝试施放:

canDeactivate(): Observable<boolean> | boolean {

    if (!this.crisis || this.crisis.name === this.editName) {

        return true;
    }
    let p = this.dialogService.confirm('Discard changes?');
    let o = <Observable<boolean>>Observable.fromPromise(p);
    return o;
}

答案 1 :(得分:3)

编译器抱怨,因为返回值o的类型为Observable<{}>。这很可能是因为您正在构建来自Observable的{​​{1}},其解析为p类型。仔细检查Promise<{}>并确保其返回值的类型为dialogService.confirm()

如果这不起作用,你可以尝试像@rinukkusu建议那样明确地施放。

答案 2 :(得分:0)

我有同样的错误,问题是我没有将Authguard作为服务注入到提供者上,而且我也没有将路由放入canActivated中的数组。确保您的AuthGuard为

`@Injectable()
export class AuthGuard implements CanActivate {
  logued: boolean = false;

  constructor(private rest: UsuarioService, private router: Router) {
    this.rest.getObservLogued().subscribe(res => {
      this.logued = res;
    });
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree  {
    let url: string = state.url;

    return this.checkLogin(url);
  }`

然后在希望设置authguard的路由中

`{ path: 'articulos', component: ArticuloComponent,

   canActivate: [AuthGuard] },`

,然后检查您是否将AuthGuard作为服务注入到app.module

providers : [AuthGuard]