# NgxCore

⚡ Try it on Stackblitz: https://stackblitz.com/edit/ngx-core-services

# Getting started

## Installation:

Install via npm package manager

```npm i ngx-core-services```

## Dependencies:

```
 @auth0/angular-jwt
 jwt-decode
```

## Usage:

### Module:

```js
import {
  NgxCoreModule,
  JwtInterceptorService,
  ErrorInterceptorService,
  AuthService,
  StorageService,
  ApiService,
  RefreshTokenInterceptor
} from "ngx-core-services";
```

```js
imports: [
...
	// Authentication server, Api server, Project name
	NgxCoreModule.forRoot({
		authHost:  'test', //environment.host,
		apiHost:  'test',//environment.host,
		project:  'test'//environment.name,
		refreshType: 0 // refresh token refresh type, if 0 it refreshes access token auto, else navigates to route ''.
	}),
...
],
providers: [
...
	providers: [
    {
		provide: LocationStrategy,
		useClass: HashLocationStrategy
	},
	{ 	provide: HTTP_INTERCEPTORS,
		useClass: JwtInterceptorService, // Intercept http requests and add jwt to the header
		multi: true
	},
    {
		provide: HTTP_INTERCEPTORS,
		useClass: ErrorInterceptorService, // Checks for http errors
		multi: true
	},
    {
		provide: HTTP_INTERCEPTORS,
		useClass: RefreshTokenInterceptor, // Refresh token interceptor
		multi: true
	},
    AuthService,
    StorageService,
    ApiService,
  ],
...
]
```

## NgxCoreModule:

```js
export interface NgxCoreConfig {
  authHost?: string; // API url for the authentication server
  apiHost?: string; // API url for the API server
  project?: string; // Project name
  refreshType?: number; // Refresh token refresh type
}
```

## ApiService:

```js
get(url: string, data?: any) // HTTP GET request
put(url: string, data?: any) // HTTP PUT request
post(url: string, data?: any) // HTTP POST request
delete(url: string, data?: any) // HTTP DELETE request
```

## StorageService:

### Cookies:

```js
setCookie((name: string), (val: string)); // Set cookie
getCookie((name: string)); // Returns with a cookie associated with the given name
deleteCookie((name: string)); // Deletes a cookie by name
clearCookies(); // Clears cookies
```

### LocalStorage:

```js
setStorage((name: string), (val: string)); // Set local storage
getStorage((name: string)); // Returns with a storage value associated with the given name
deleteStorage((name: string)); // Deletes a storage by name
clearStorage(); // Clears the storage
```

## AuthService:

```js
public  canActivate(route: ActivatedRouteSnapshot):boolean // Route guard
public  isAuthenticated(): boolean // Has token and isvalid
public  getToken() // Returns the saved access_token
public  login(url: string, data) // User login, if data['refreshType'] is given then sets refreshType (concats url to authHost)
public  getRole() // Get user role from access_token identity
public  getUsername() // Get username from access_token identity
public  getName() // Get name from access_token identity
public  getUserData() // Get user data from access_token identity
public  change(data: any) // Data change subject
public  logout(url: string, data?) // User logout, cookie and storage clear.
```

## JwtInterceptorService:

```js
intercept((request: HttpRequest<any>), (next: HttpHandler)); // sets the access_token or refresh_token
```

## ErrorInterceptorService:

```js
intercept((request: HttpRequest<any>), (next: HttpHandler)); // throws error if something bad happens
```

## RefreshTokenInterceptorService:

```js
intercept((request: HttpRequest<any>), (next: HttpHandler)); // sets the refresh token if access_token has expired
```

## AppState

```js
setAppState(); // Sets localstorage key, and loggedIn
getAppState(); // Returns app state
getAppStateByKey(key: string); // Returns app state by key
changeAppState(obj: any); // Changes app state e.g.: obj={'loggedIn': true}
```

### Example:
##### App Component:
```js
import { AppStateService } from "ngx-core-services";
...
constructor(private appStateService: AppStateService){
}
ngOnInit(): void {
  this.appStateService.setAppState();
}
```

## ViewState

```js
getViewState(); // Sets the viewState - only use it in the view constructor!
setViewState(obj: any); // Returns the viewState object
getViewStateByKey(key: string); // Returns data that maches the given parameter.
getView(); // Returns the current view.
changeViewState(obj: any, history?); // Changes the view state. Sets the goven data and history, emits the current change.
```
### Example:
##### View1:
```js
import { ViewStateService } from "ngx-core-services";
...
constructor(private viewStateService: ViewStateService) {
  this.viewStateService.setViewState({view: 'View1'});
}
```
##### Component1:
```js
test = 0;
constructor(private viewStateService: ViewStateService) {
    this.viewStateService.datachange.subscribe(data => {
        this.test = data.get('test');
        // write your code
    });
}
...
btnTest_Click() {
    this.test++;
    this.viewStateService.changeViewState({ test: this.test, test: 'test' }, 'btnTest_Click'); // data object and history, you don't need to change the view's name, only give the data and the history.
}
```
