我在获取 Behavior Subject 以更新 .next(value) 调用中的订户时遇到问题。
我是打字稿的新手,但我想我一定是遗漏了一些小东西。从我所见,这似乎是正确的。
网站上有很多这样的问题,但没有一个能解决我的问题。这是一个例子。订阅者没有收到来自 .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 始终为假,但如果我在此下放置另一个订阅者调用并打印另一个变量,我可以看到它现在实际上是真的并且它已正确更新。我是否在这里遗漏了导致已验证身份无法更新的内容?
一些额外的信息。这是我的 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 guard 服务的路由(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 { }
最后这里是调用的函数,它实际上将身份验证主题设置为 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)
}
});
}