- NativeScript for Angular Mobile Development
- Nathan Walker Nathanael J. Anderson
- 592字
- 2021-07-02 18:41:49
Create AuthService to help handle the authenticated state of our app
One important consideration for our AuthService is to understand that certain components in our app may benefit from getting notified when the authenticated state changes. This is a perfect use case to utilize RxJS. RxJS is a very powerful library that is used to simplify dealing with changing data and events using observables. An observable is a data type that you can use not only to listen to events, but filter, map, reduce, and run sequences of code against anytime something occurs. By using observables, we can simplify our asynchronous development dramatically. We will use a specific type of observable called the BehaviorSubject to emit changes that our components could subscribe to.
Create app/modules/core/services/auth.service.ts and add the following:
// angular
import { Injectable } from '@angular/core';
// lib
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
// app
import { DatabaseService } from './database.service';
import { LogService } from './log.service';
@Injectable()
export class AuthService {
// access our current user from anywhere
public static CURRENT_USER: any;
// subscribe to authenticated state changes
public authenticated$: BehaviorSubject<boolean> =
new BehaviorSubject(false);
constructor(
private databaseService: DatabaseService,
private logService: LogService
) {
this._init();
}
private _init() {
AuthService.CURRENT_USER = this.databaseService
.getItem(DatabaseService.KEYS.currentUser);
this.logService.debug(`Current user: `,
AuthService.CURRENT_USER);
this._notifyState(!!AuthService.CURRENT_USER);
}
private _notifyState(auth: boolean) {
this.authenticated$.next(auth);
}
}
We have a few interesting things going on here. We are putting two other services we designed to work right away, LogService and DatabaseService. They are helping us check whether a user was saved/authenticated as well as log that result.
We are also calling on a private _init method when our service gets constructed via Angular's dependency injection system. This allows us to immediately check whether an authenticated user exists in our persistent store. Then, we call a private reusable method _notifyState, which will emit true or false on our authenticated$ observable. This will provide a nice way for other components to easily get notified when the auth state changes by subscribing to this observable. We have made _notifyState reusable because our login and register methods (to be implemented in the future) will be able to use it when the results are returned from modals we may display in the UI.
We can now easily add AuthService to our PROVIDERS and we don't need to do anything else to ensure it's added to our CoreModule because our PROVIDERS are already added to the CoreModule.
All we need to do is modify app/modules/core/services/index.ts and add our service:
import { AuthService } from './auth.service';
import { DatabaseService } from './database.service';
import { LogService } from './log.service';
export const PROVIDERS: any[] = [
AuthService,
DatabaseService,
LogService
];
export * from './auth.service';
export * from './database.service';
export * from './log.service';
WAIT! There is one important thing we want to do to ensure our AuthService initializes!
Angular's dependency injection system will only instantiate a service that is injected somewhere. Although we have all our services specified as providers in our CoreModule, they will not actually be constructed until they are injected somewhere!
Open app/app.component.ts and replace its contents with this:
// angular
import { Component } from '@angular/core';
// app
import { AuthService } from './modules/core/services';
@Component({
selector: 'my-app',
templateUrl: 'app.component.html',
})
export class AppComponent {
constructor(private authService: AuthService) { }
}
We inject our AuthService by specifying it as an argument to our component's constructor. This will cause Angular to construct our service. All subsequent injects throughout our code will all receive the same singleton.
- JavaScript前端開發模塊化教程
- 程序員面試白皮書
- Network Automation Cookbook
- Designing Hyper-V Solutions
- 深度學習:算法入門與Keras編程實踐
- JavaScript動態網頁開發詳解
- 軟件項目管理實用教程
- iOS應用逆向工程(第2版)
- Hands-On Reinforcement Learning with Python
- C#程序設計(項目教學版)
- Scala for Machine Learning(Second Edition)
- Hands-On Neural Network Programming with C#
- Xcode 6 Essentials
- Learning iOS Security
- Java Web開發實例大全(基礎卷) (軟件工程師開發大系)