行为主体未更新.next(value)上的订户

时间:2019-06-03 06:57:11

标签: typescript ionic4 subscribe behaviorsubject auth-guard

我在获取行为主体以更新.next(value)调用上的订户时遇到问题。

我是打字稿新手,但我想我一定只是想念一些小东西。根据我所见,这似乎是正确的。

网站上有很多类似的问题,但是都没有解决我的问题。这是一个例子。 Subscriber doesn't receive value from .next()

RestService仅放在app.module.ts提供程序数组中。

身份验证防护文件(services / auth-guard.service.ts)


authenticated = false;

...

    ngOnInit(){
        this.restService.isLoggedIn().subscribe({
            next: result => {
                this.authenticated = result;
            }
        });
    }

...

    canActivate(route: ActivatedRouteSnapshot): boolean{

        console.log(this.authenticated);

        if(!this.authenticated){
            this.router.navigate(['login']);
        }
        return this.authenticated;
    }
}

休息服务文件(services / rest.service.ts)的一部分

import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { RequestOptions } from '@angular/http';
import { Injectable } from '@angular/core';
import { Storage } from  '@ionic/storage';
import { Observable, BehaviorSubject } from  'rxjs';
import { User } from  'src/app/Interfaces/user';
import { tap } from 'rxjs/operators';

...

authSubject  =  new  BehaviorSubject(false);

...

public _setAuthSubject(value){
    this.authSubject.next(value);
 }

public isLoggedIn() {
    return this.authSubject.asObservable();
  }

在canActivate中,我有一个控制台日志,该日志显示this.authenticated始终为false,但是如果我放置另一个订户调用并在此下打印另一个变量,则可以看到它现在实际上是正确的,并且已正确更新。我是否在这里丢失了一些导致无法更新身份验证的内容?

一些其他信息。这是我的app.module.ts

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    HttpClientModule,
    IonicStorageModule.forRoot()
  ],
  providers: [
    AuthGuardService,
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    SQLite,
    SQLitePorter,
    RestService,
  ],
  bootstrap: [AppComponent]
})

还有调用auth保护服务的路由(app-routing.module.ts)

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AuthGuardService } from './services/auth-guard.service';

const routes: Routes = [
  { path: '', loadChildren: './tabs/tabs.module#TabsPageModule', canActivate: [AuthGuardService]},
  { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

最后是调用的函数,该函数实际上将auth主题设置为true(login / login.page.ts)

constructor(
    public menu: MenuController,
    private restService: RestService,
    private router: Router,
    private storage: Storage
  ) { }


  async login(form){

    this.restService.login(form.value).subscribe({
      next: response => {
        console.log(response)
        if(response.access_token){
          this.storage.set("ACCESS_TOKEN", response.access_token);
          this.restService._setToken(response.access_token);
          this.restService._setAuthSubject(true);
        }
        this.router.navigateByUrl('');
      },
      error: err => {
        console.log('ERROR!: ', err)
      }
    });
  }

2 个答案:

答案 0 :(得分:0)

使用以下代码修改了AuthGuard。服务无法在ngOnInit中包含代码,我不知道! Nooby错误...感谢您对@ingkevin和@lchraf的所有帮助。

SELECT CONCAT("YEAR ", FORMAT(WindowsLogs.Year, "00")), FORMAT(COUNT(*), "00")
FROM WindowsLogs
WHERE WindowsLogs.Date=cast(convert(varchar(10), getdate(), 105) as datetime)
GROUP BY WindowsLogs.Year

ngOnInit已删除。

答案 1 :(得分:0)

我已经在BehaviourSubject上创建了一个演示,请看一下可能会有助于解决您的问题。

https://stackblitz.com/edit/behavioursubject-angular-demo