官术网_书友最值得收藏!

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. 

主站蜘蛛池模板: 湖州市| 峨眉山市| 馆陶县| 田林县| 鸡西市| 钟祥市| 甘泉县| 长宁区| 荔浦县| 泽普县| 霍林郭勒市| 库车县| 青州市| 诸城市| 诏安县| 资阳市| 沙田区| 侯马市| 罗源县| 乡宁县| 大港区| 潼关县| 江安县| 资中县| 泰和县| 新巴尔虎右旗| 泉州市| 同德县| 饶平县| 铁岭县| 夏河县| 雷州市| 土默特右旗| 涿州市| 桐梓县| 建阳市| 浦东新区| 沁水县| 万州区| 大名县| 东乡族自治县|