#angular #ionic-framework #module
#angular #ionic-framework #модуль
Вопрос:
Я получил эту ошибку при запуске приложения ionic, я не уверен, что я делаю, но пытаюсь получить api аутентификации jwt в ionic
Функция canActive была похожа, но я получил ошибку, поэтому я ее меняю.
CanActivate(): boolean {
return this.authService.isAuthenticated();
}
NullInjectorError: No provider for Storage!
NullInjectorError: R3InjectorError(LoginPageModule)[AuthenticationService -> AuthenticationService -> Storage -> Storage -> Storage]:
NullInjectorError: No provider for Storage!
at NullInjector.get (core.js:915)
at R3Injector.get (core.js:11082)
at R3Injector.get (core.js:11082)
at R3Injector.get (core.js:11082)
at injectInjectorOnly (core.js:801)
at ɵɵinject (core.js:805)
at Object.AuthenticationService_Factory [as factory] (ɵfac.js? [sm]:1)
at R3Injector.hydrate (core.js:11249)
at R3Injector.get (core.js:11071)
at NgModuleRef$1.get (core.js:24199)
at resolvePromise (zone-evergreen.js:798)
at resolvePromise (zone-evergreen.js:750)
at zone-evergreen.js:860
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:27425)
at ZoneDelegate.invokeTask (zone-evergreen.js:398)
at Zone.runTask (zone-evergreen.js:167)
at drainMicroTaskQueue (zone-evergreen.js:569)
мой код службы аутентификации:
import { Platform } from '@ionic/angular';
import { BehaviorSubject } from 'rxjs';
import { Storage } from '@ionic/Storage';
import { HttpClient } from '@angular/common/http';
const TOKEN_KEY ='auth-token';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
authenticationState = new BehaviorSubject(false)
constructor( private storage: Storage, private plt: Platform, private http: HttpClient) {
this.plt.ready().then(()=>{
this.chechToken();
});
}
login(user){
this.http.post('http:127.0.0.1:8001/api/user', user).subscribe(res =>{
return this.storage.set(TOKEN_KEY,`Bearer ${res['token']}`).then( res =>{
this.authenticationState.next(true);
});
});
}
logout(){
return this.storage.remove(TOKEN_KEY).then ( () =>{
this.authenticationState.next(false);
});
}
isAuthenticated(){
return this.authenticationState.value;
}
chechToken(){
return this.storage.get(TOKEN_KEY).then ( res =>{
if (res){
this.authenticationState.next(true);
}
});
}
}
моя служба аутентификации
import { AuthenticationService } from './authentication.service';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthenticationService) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
return this.authService.isAuthenticated();
}
}
мой код модуля приложения
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Storage } from '@ionic/storage';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
это учебное пособие: https://www.youtube.com/watch?v=o35Cy5ZkYU0amp;t=3s
Ответ №1:
Указали ли вы IonicStorageModule
using forRoot в своем AppModule?
Смотрите Документы:
@NgModule({
declarations: [
// ...
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
// Without this, Storage won't be available!
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
// ...
],
providers: [
// ...
]
})
export class AppModule {}
Комментарии:
1. да, я запустил плагин ionic cordova, добавил cordova-sqlite-storage и добавил storge в AppModule, и его работа спасибо