3.5.6 • Published 3 years ago

starter-ng-lib v3.5.6

Weekly downloads
273
License
-
Repository
-
Last release
3 years ago

Starter Angular Library

Overview

starter-ng-lib is a package for Angular applications that contains a variety of base implementations for commonly used modules from various authentication flows to alert services and date helpers.

Modules currently included:

Auth Module

  • Authentication Flows - Auth Proxy (a proxy that handles delegation of auth to the flows defined below) - OpenIddict - AWS Cognito

  • Authentication Extras - Base User Interface (contains an implementation per auth flow) - Base User Service - Auth Interceptor - Error Interceptor - Auth Guard

API Module

  • Generic API Service

Alert Module

  • Alert Service

Helper Module

  • Helper Services - Date Service - Scroll Service

Angular Version Support

starter-ng-libAngular
1.x.x7.0.0
2.x.x7.0.0
3.x.x9.0.0

Versions & Change Logs

Version 3.5.4

  • Publish fix.

Version 3.5.3

  • Bug fix for errors thrown when not using the Okta auth method.

Version 3.5.2

  • Fixed issue on loadSession that was not properly checking for an empty session.

Version 3.5.1

  • Update the session handlers and move to the interface/proxy for access in clients.
  • Remove unneeded load session calls.

Version 3.5.0

  • Implemented Okta Login Service that will interact with an Okta Installation and allow for full-featured authentication.
  • This includes the assumption that the client utlizing this lib is using the Okta Sign-in Widget.
  • The Okta Auth Service will automatically handle the callback from a sign-in attempt from the Okta Sign-in Widget.
  • The Okta Auth Service handles the login process, setting tokens, getting/setting the user, as well as refreshing of tokens.

Version 3.4.1

  • Fixed a multiselect component bug that caused single-select components to not emit change events when deselecting.

Version 3.4.0

  • Added the complete data export service.

Version 3.3.5

  • Added DefaultControlText input to the multi select control to allow for defaulting the base display text on the control to better describe the control in some cases.

Version 3.3.4

  • Reworked the multi select component to render option values as HTML.

Version 3.3.3

  • Added a selectedValueTransform input to the multi select component for transforming the display text in the selection box.
  • Added a data export service to convert json to csv.
  • Added a file download service to prompt users for file downloads with base64 file strings.

Version 3.3.2

  • Added serverside searching to the multiselect component.
  • Added a new patch request to the api service.

Version 3.3.1

  • Fixed bug with ngb datepicker validation messages with the validate directive.
  • Fixed a bug causing the "select all" checkbox to remain checked after paging on the grid component.

Version 3.3.0

  • Added direct support for maintenance tables to the api service.

Version 3.2.4

  • Fixed a grid component bug that caused row striping to change when the grid loader was displayed.

Version 3.2.3

  • Fixed some grid component bugs with the loader and ellipsis.

Version 3.2.2

  • Added the ability to show the grid component loader without text.

Version 3.2.1

  • Added the ability to set icons as grid component headers.
  • Added a loading input the the grid component with a built-in loading state and animation.

Version 3.2.0

  • Added selectable rows to the grid component.
  • Added breakpoint based column hiding to the grid component.
  • Fixed some ListColumn display issues with the grid component.
  • Fixed some grid component functionality that wasn't working properly on the mobile stacked grid.

Version 3.1.2

  • Added the ability to set the current page number via config for the grid component.
  • Added new grid component inout to manually trigger an update.

Version 3.1.1

  • Fixed a multiselect component bug that caused the selected options state to be incorrect when changing the options input after the selectedOptions input.

Version 3.1.0

  • Feature updates to the multiselect component.

    • The multiselect now accepts a proper selectedOptions input that will update the component with the passed options. Works with adding and removing selections.
    • The multiselect now properly clears the search and scroll position of the dropdown upon closing it.
    • The multiselect now shows the proper selection state of options while searching.
    • The multiselect has a new disabled input that will disable the input if true is passed. This can update after initialization.

Version 3.0.2

  • Fixed an issue causing a crash when setting the auth method to OpenIddict without having Cognito auth params set in the auth config.

Version 3.0.1

  • Patch for package rebuild.

Version 3.0.0

  • Updated all packages to Angular 9.
  • Added ApiService.

Version 2.4.1

  • Updated README to show Angular version support.

Version 2.4.0

  • Added new multiselect component.
  • Added new tabs component.

Version 2.3.8

  • Updated grid component to fix a paging bug that showed the wrong bounds for the records indicator.

Version 2.3.7

  • Updated grid component to include better paging controls and records indicator.

Version 2.3.6

  • Small tweak to timeouts during session expiration logout flow.

Version 2.3.5

  • Added Cognito Token Validation such that the expiry time of the Cognito ID Token will be tracked and will warn the user when their session is nearly expiration.

Version 2.3.4

  • Fixed auth interceptor incorrectly appending the access token when using Cognito auth.
  • Added new grid component column types:
    • HTML
    • List
  • Added dataTransform option to all grid component column types.

Version 2.3.3

  • Fixed grid component with local paging not initially processing ellipsis tooltips.

Version 2.3.2

  • Fixed grid component stack not properly handling local paging.
  • Fixed grid component paging buttons not having default styling.

Version 2.3.1

  • Fixed bug that caused the grid component to break when loading data after component construction.

Version 2.3.0

  • Modified config format for the grid component.
  • Added local paging and sorting to the grid component.
  • Added boolean-based icon columns to the grid component.
  • Updated the default grid component styles.

Version 2.2.4

  • Updated the Cognito Service layer to fix issues with previous release and handle the Cognito OAuth flow properly.
  • Added grid component.

Version 2.2.3

  • Updated the Cognito Service layer to include the authenticate by URL functionality from the cognito-auth-js library.

Version 2.2.2

  • Reworked Auth Interceptor to properly handle refreshing of the access_token such that now parallel API requests will be properly handled and wait for the refresh to occur before attempting to release the request.

Version 2.2.1

  • Fixes after failed merge and publish to incorporate fixes from versions 2.1.1 and 2.1.2

Version 2.2.0

  • Added features to the form validate directive.
    • Added a 'messageContainer' input that allows you to specify a different element that messages will be appended to.
    • Added error message support for ngb datepickers.

Version 2.1.2

  • Added event emitter for successful login event.

Version 2.1.1

  • Update the Validation Directive to properly handle disabled controls.

Version 2.1.0

  • Added features to the placeholder directive.
    • Added a 'phDataPath' input to allow nested data to be inserted after load.
    • Added a 'phElement' input to allow separate elements to be hidden/shown in place of the placeholder element.

Version 2.0.4

  • Fixed a bug that caused all logout methods to trigger as the SessionsExpired method.

Version 2.0.3

  • Fixed another authentication issue with refresh_token storage including removing rolling tokens option.
  • Updated the Logout event emitter to require a LogoutMethod Enum to simplify client-side handling of logout events.

Version 2.0.2

  • Fixed issue with not properly setting id_token in storage.

Version 2.0.1

  • Fixed issue with properly retrieving tokens from local storage when they are not present in memory.

Version 2.0.0

  • Added Id_Token management process to the OpenIddict service such that it will automatically detect when the token is nearing expiration and present the user with an option to refresh. - BREAKING CHANGES - Modified the IAuthTokens interface to remove the generic "expires_at" seeing as we want to track both Id_Token and Access_Token expiration. - Modified both the Cognito/OpenIddict tokens models to incorporate access_expires_at as well as id_expires_at.
  • Added Access_Token management process to the Auth Interceptor such that whenever a request is made to the API, the process will automatically refresh the access_token (forcing short lived access_tokens).
  • Added "Logout" emitter such that when the library sends and recieves a successful Token Revocation response, the system will emit that a successful logout has occured to allow any front-end client to process that event how it see's fit.
  • Added process to stamp roles on the BaseUser object after successful authentication.

Version 1.2.2

  • Added ApiResponse model.
  • Fixed how the authenticate function in the OpenIddict service handled the API response on failed auth attempts.
  • Renamed GenericApiService to ApiEntityService.

Version 1.2.1

  • Fixed bug loading OpenIddict session from local storage.

Version 1.2.0

  • Added forms module.
    • Added validators.
    • Added validate directive.
    • Added validation service.
  • Added placeholder directive in helper directives.
  • Updated OpenIddictService to save session upon authenticating and load session when checking isAuthenticated.

Version 1.1.2

  • Fixed wording and typos in README

Version 1.1.1

  • Updated README to improve section spacing

Version 1.1.0

  • Updated BaseUser to an interface (IBaseUser) with implementations for Cognito and OpenIddict. - Included a new IAuthTokens interface with implementations per auth flow as well.
  • Updated AuthSubject with additional password-related functions.
  • Updated method signatures in AuthSubject to take in generic objects so each service can take in its own values per function.
  • Updated UserService to work with the new IBaseUser.
  • Renamed ETGAuthService to AuthProxy.
  • Updated AuthProxy, CognitoService, and OpenIddictService to work with the new AuthSubject, IBaseUser, and UserService.
  • Implemented OpenIddict auth flow Login, Register, getCurrentUser, and IsAuthenticated functions.

Version 1.0.0

  • Updated to new 'starter-ng-lib' format.

Old etg-ng-base-versions:

Version 0.2.0

  • Added auth config to AuthVars that is used by auth subjects to configure endpoints.
  • Updated required auth config values to OpenIddictService.
  • Added auth interceptor blacklist to AuthVars to allow specified values to be ignored when adding the access token to outgoing requests.
  • Updated AuthInterceptor to use the blacklist to determine if the token should be added.

Version 0.1.0

  • Added AlertService.
  • Fixed AuthInterceptor to properly append the access token to outgoing requests.

Installation

Using npm:

$ npm install --save starter-ng-lib

Peer Dependencies

In order for this package to work, you must have the following peer dependencies installed in your application:

  • "@angular/common": "^7.2.0"

  • "@angular/core": "^7.2.0"

  • "sweetalert2": "^8.8.3"

  • "jwt-decode": "^2.2.0"

  • "amazon-cognito-identity-js": "^3.0.7"

  • "aws-sdk": "^2.418.0"

  • "moment": "^2.24.0"

  • "jquery": "^3.4.1"

Auth Module

The Auth module included in starter-ng-lib is built abstractly using a proxy pattern to allow different authentication methods to be used and swapped in/out easily. The AuthProxy service provides a top-level interface to be interacted with in any client application. The service implements a common AuthSubject interface with various auth functions such as authenticate, logout, getAccessToken, etc. All individual auth subjects, such as OpenIddict or AWSCognito, also implement the same interface to provide common functionality with different implementations. The auth proxy combined with the AuthVars service allows authentication to be easily inserted into an application without muddling with the implementation details per-project.

Setup

To start using the AuthService, you need to set up a couple things in your app.component.ts such as importing the AuthProxy and configuring a few values.

1. AuthProxy: Imports and Injections

To start integrating the auth proxy, import AuthProxy from this package and inject it into your app.component.ts constructor.

After the service is injected you can specify which authentication method you will be using, and define the auth vars for it to initialize. Authentication methods represent the various different authentication subjects/flows with their own implementations of the AuthSubject interface. For example, OpenIddictService and CognitoService are both examples of auth methods.

Import the AuthMethod enum from this package so you have reference to the different options available.

With AuthProxy and AuthMethod imported, your code may look something like this:

import { Component } from  '@angular/core';
import { AuthProxy, AuthMethod } from  'starter-ng-lib';

@Component({
	selector:  'app',
	templateUrl:  './app.component.html',
	styleUrls: ['./app.component.scss']
})
export  class  AppComponent {
	constructor(
		private  authProxy:  AuthProxy
	) { }
}

2. Setting AuthVars

In order for the auth method you're using to work properly, you must specify certain values for it to use. These values represent connection strings, resource IDs, API keys, etc.

These values can be set in the AuthVars service directly, but the AuthProxy also has functons to interact with auth vars, so let's use those. The functions you can use to set auth variables are setAuthConfig(), addToAuthConfig(), and removeFromAuthConfig(). Call these functions as you wish to set key-value pairs as values to be used by the authentication method you'll be using.

Different authentication methods require different variables to be set, the required variables for each method are defined as follows:

2a. Cognito AuthVars

The following AuthVars are required for AWS Cognito:

  • user_pool_id = the user pool id of the Cognito user pool you are using
  • app_client_id = the app client id of the app client you created for your application on Cognito
  • region = the region that your Cognito pool is created in
  • access_key_id = the access key of an IAM user with full access to your Cognito pool
  • secret_access_key = the secret key of an IAM user with full access to your Cognito pool

Cognito code example:

import { Component } from  '@angular/core';
import { AuthProxy, AuthMethod } from  'starter-ng-lib';

@Component({
	selector:  'app',
	templateUrl:  './app.component.html',
	styleUrls: ['./app.component.scss']
})
export  class  AppComponent {
	constructor(
		private  authProxy:  AuthProxy
	) {
		this.authProxy.setAuthConfig({
			user_pool_id: <user pool id here>,
			app_client_id: <client id here>,
			region: <region here>,
			access_key_id: <access key id here>,
			secret_access_key: <secret access key here>
		});
	}
}
2b. OpenIddict AuthVars

The following AuthVars are required for OpenIddict:

  • api_url_base = the base url of the API to make requests to for authentication calls. Example: "http://localhost:5000"
  • api_url_extension = an extension to append to the end of most auth API calls. The only endpoint this isn't appended to is logout function as it uses OpenIddicts built-in "revoke" endpoint. Example: "/api/v1"
  • grant_type = the type of auth grant that the backend is expecting. For example: "password"
  • scope = the scope defined for authenticating. For example: "openid offline_access"
  • client_id = the ID of the client you are authenticating from. For example: "mystarter"

OpenIddict code example:

import { Component } from  '@angular/core';
import { AuthProxy, AuthMethod } from  'starter-ng-lib';

@Component({
	selector:  'app',
	templateUrl:  './app.component.html',
	styleUrls: ['./app.component.scss']
})
export  class  AppComponent {
	constructor(
		private  authProxy:  AuthProxy
	) {
		this.authProxy.setAuthConfig({
			api_url_base: <api url base here>,
			api_url_extension: <api url extension here>,
		  	grant_type: <grant type here>,
		  	scope: <scope here>,
		  	client_id: <client id here>
		});
	}
}

3. Setting the Auth Method

The last things that must be done to start using authentication is to actually set which auth method you're using. This can be done with the setAuthMethod() function in the AuthProxy.

Call the setAuthMethod() function and pass it an option from the AuthMethod enum to defined which auth method you will use.

3a. Cognito Auth Method

this.authProxy.setAuthMethod(AuthMethod.Cognito);

import { Component } from  '@angular/core';
import { AuthProxy, AuthMethod } from  'starter-ng-lib';

@Component({
	selector:  'app',
	templateUrl:  './app.component.html',
	styleUrls: ['./app.component.scss']
})
export  class  AppComponent {
	constructor(
		private  authProxy:  AuthProxy
	) {
		this.authProxy.setAuthConfig({
			user_pool_id: <user pool id here>,
			app_client_id: <client id here>,
			region: <region here>,
			access_key_id: <access key id here>,
			secret_access_key: <secret access key here>
		});
		
		this.authProxy.setAuthMethod(AuthMethod.Cognito);
	}
}
3b. OpenIddict AuthMethod

this.authProxy.setAuthMethod(AuthMethod.OpenIddict);

import { Component } from  '@angular/core';
import { AuthProxy, AuthMethod } from  'starter-ng-lib';

@Component({
	selector:  'app',
	templateUrl:  './app.component.html',
	styleUrls: ['./app.component.scss']
})
export  class  AppComponent {
	constructor(
		private  authProxy:  AuthProxy
	) {
		this.authProxy.setAuthConfig({
			api_url_base: <api url base here>,
			api_url_extension: <api url extension here>,
		  	grant_type: <grant type here>,
		  	scope: <scope here>,
		  	client_id: <client id here>
		});
		
		this.authProxy.setAuthMethod(AuthMethod.OpenIddict);
	}
}

Auth Method Usage

With authentication implemented in your client application using one of the available auth methods, you can start using it to make calls and authorize users with your application. Below are the differen functions available through the AuthProxy and what parameters each AuthMethod are expecting for those functions. Note: Be sure to call the functions through the AuthProxy and avoid calling the individual auth services directly. The exception to this would be when you need to call a more specific function that doesn't exist in the AuthProxy.

Cognito Auth Usage

authenticate(authData: any): Promise

Attempts to authenticate a user with the system. If successful, the CognitoUser will be returned with user attributes and token data pre-populated. Expected Parameters:

  • username: string = the username of the user to authenticate
  • password: string = the password of the user to authenticate
logout(): Promise

Logs the current user out of thr system, marking them as unauthorized. Expected Parameters:

  • None
register(registerData: any): Promise

Attemps to register a new user with the system. The result of this varies by implementation as some auth methods do not return a newly created user after registration, this is one of them. Expected Parameters:

  • email: string = the email of the new user to register
  • username: string = the username of the new user to register. (for Cognito, this is what will be used to login)
  • password: string = the password of the new user to register
  • attributes: any = an object containing additional attributes that Cognito is expecting. The specifics of these attributes is on a case-by case basis. By default this can be '{}'. As a special case for this parameter, if you include a property named "group" with a string value, the new user will automatically get added to the specified group upon registration.
forgotPassword(forgotPasswordData: any): Promise

Initiates a forgot password flow with the auth method. This will typically trigger an email to verify the user's account before actually updating the password. Expected Parameters:

  • username: string = the username of the user to initiate a forgot password flow for
changePassword(changePasswordData: any): Promise

Change a users password to a new one when the previous password is still known. Expected Parameters:

  • username: string = the username of the user to change the password for
  • existingPassword: string = the old password
  • newPassword: string = the new password to set
getCurrentUser(): Promise

Retrieve the currently authenticated user of the system. Returns an instance of CognitoUser. NOTE: This method returns a promise as this method is intended to get the user fresh from the auth server/database. To simply get the currently stored user immedietly without a promise, use the UserService defined below. Expected Parameters:

  • None
isAuthenticated(): Promise

Returns true or false if the current user is authenticated. Also returns false if there is no current user. Expected Parameters:

  • None

OpenIddict Auth Usage

authenticate(authData: any): Promise

Attempts to authenticate a user with the system. If successful, the OpenIddictUser will be returned with user attributes and token data pre-populated. Expected Parameters:

  • username: string = the username of the user to authenticate
  • password: string = the password of the user to authenticate
logout(): Promise

Logs the current user out of thr system, marking them as unauthorized. Expected Parameters:

  • None
register(registerData: any): Promise

Attemps to register a new user with the system. The result of this varies by implementation as some auth methods do not return a newly created user after registration, this is one of them. Expected Parameters:

  • username: string = the email of the new user to register
  • firstName: string = the first name of the new user to register
  • lastName: string = the last name of the new user to register
  • password: string = the password of the new user to register
forgotPassword(forgotPasswordData: any): Promise

Initiates a forgot password flow with the auth method. This will typically trigger an email to verify the user's account before actually updating the password. Expected Parameters:

  • email: string = the email of the user to initiate a forgot password flow for (this is the same as the username for OpenIddict)
changePassword(changePasswordData: any): Promise

Change password in OpenIddict is done through account verification without knowledge of the previous password. An email will be sent with a code to verify the account, then the new password can be set. Expected Parameters:

  • id: string = the id of the user to change the password for
  • code: string = the verification code from an email
  • newPassword: string = the new password to set
getCurrentUser(): Promise

Retrieve the currently authenticated user of the system. Returns an instance of OpenIddictUser. NOTE: This method returns a promise as this method is intended to get the user fresh from the auth server/database. To simply get the currently stored user immedietly without a promise, use the UserService defined below. Expected Parameters:

  • None
isAuthenticated(): Promise

Returns true or false if the current user is authenticated. Also returns false if there is no current user. Expected Parameters:

  • None

Interceptors

starter-ng-lib includes two interceptors that can be used to modify outgoing requests and responses. The two included are the AuthInterceptor and the Error Interceptor.

To use either interceptor, open your application's app.module file. Start by importing the HTTP_INTERCEPTORS module from angular, and importing any starter-ng-lib interceptors you wish to use.

import { HTTP_INTERCEPTORS } from  '@angular/common/http';
import { AuthInterceptor, ErrorInterceptor } from  'starter-ng-lib';

With the needed components imported, add the interceptors as providers in your module.

@NgModule({
	declarations: [ ... ],
	imports: [ ... ],
	providers: [
		{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
		{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
	],
	bootstrap: [ ... ]
})
export  class  AppModule { }

The interceptors will now work automatically. Read the information below on each interceptor to find out what they do.

Auth Interceptor

The auth interceptor will automatically append the Authorization header with the current user's access token to all outgoing requests. Requests with certain keywords in their URLs can be blacklisted by adding the authInterceptorBlacklist array in the AuthVarsService (or AuthProxy). In short, you can add blacklisted keywords like so (preferably in your app.component.ts along with your auth method setup):

this.authProxy.setAuthInterceptorBlacklist([
	"Token",
	...
]);

Error Interceptor

The error interceptor will monitor all outgoing request responses. If a response has a status code of 401 (Unauthorized), the interceptor will automatically logout the current user and reload the page. All error codes will be logged to console with some useful information.

User Service

The UserService in the auth module maintains reference to the currently authenticated IBaseUser. The user is set automatically upon successful authentication through any AuthMethod. The service also contains various functions to retrieve and modify the stored user.

UserService Functions

public getCurrentUser(): IBaseUser

Returns the currently stored user directly, without a promise. If there is a user stored it will be returned immedietly, if no user is stored, it will return undefined, the user will not be retrieved from any server. To retrieve an authenticated user that hasn't yet been stored, use the authenticate function in the AuthProxy. Expected Parameters:

  • None
public setCurrentUser(user: IBaseUser): void

Sets the user that is stored in the service. The other functions in this servce will then work with that single stored user. Expected Parameters:

  • user: IBaseUser = an instance of IBaseUser that represents the currently authenticated user with the system
public getAccessToken(): any

Returns the access token for the currently authenticated user. If there is no authenticated user, this will return undefined. Expected Parameters:

  • None
public getIdToken(): any

Returns the id token for the currently authenticated user. If there is no authenticated user, this will return undefined. Expected Parameters:

  • None
public clearUser(): any

Clears the currently stored user and explicitly sets it to null. Expected Parameters:

  • None

IBaseUser and IAuthTokens Models

IBaseUser

IBaseUser is an interface with common auth user fields. Each individual AuthMethod will provide its own implementation of this interface to store the authenticated user and return it. Interface Fields:

  • id: any = the id of the user
  • username: any = the username of the user
  • tokens: IAuthTokens = the set of authentication tokens for the user (see IAuthTokens below)
  • roles: IUserRole[] = an array of user roles (not yet implemented)
  • attributes: any = a generic object containing various user attributes (name, phone, etc)
IAuthTokens

IAuthTokens is an interface with common token fields that will be kept for all authenticated users. Each individual AuthMethod will provide its own implementation of this to account for any additional token data. Interface Fields:

  • access_token: any = the access token used for API authorization
  • id_token: any = the id token used to identify the user
  • expires_at: any = the date/time that the tokens will expire (no implied format at the interface level so this is type "any")

CognitoUser and CognitoTokens Models

CognitoUser

The CognitoUser model implements the IBaseUser interface and extends it with some additional Cognito-specific fields. The id and emial fields will be automatically populated from the Cognito attributes list. Model Fields:

  • id: string = the id of the user
  • username: string = the username of the user
  • email: string = the email fo the user
  • tokens: CognitoTokens = the set of authentication tokens for the user (see CognitoTokens below)
  • roles: IUserRole[] = an array of user roles (not yet implemented)
  • attributes: any = a generic object containing various user attributes (name, phone, etc).
CognitoTokens

The CognitoTokens model implements the IAuthTokens interface and extends it with a few additional Cognito-specific fields. Model Fields:

  • access_token: string = the access token used for API authorization
  • id_token: string = the id token used to identify the user
  • refresh_token: string = the refresh token used to refresh the user's session
  • expires_at: number = the unix timestamp representing the date/time that the tokens will expire

OpenIddictUser and OpenIddictTokens Models

OpenIddictUser

The OpenIddictUser model implements the IBaseUser interface and follows it closely. Model Fields:

  • id: string = the id of the user
  • username: string = the username of the user
  • tokens: OpenIddictTokens = the set of authentication tokens for the user (see OpenIddictTokens below)
  • roles: IUserRole[] = an array of user roles (not yet implemented)
  • attributes: any = a generic object containing various user attributes (name, phone, etc).
OpenIddictTokens

The OpenIddictTokens model implements the IAuthTokens interface and extends it with a few additional OpenIddict-specific fields. Model Fields:

  • access_token: string = the access token used for API authorization
  • id_token: string = the id token used to identify the user
  • refresh_token: string = the refresh token used to refresh the user's session
  • expires_at: number = the unix timestamp representing the date/time that the tokens will expire
  • token_type: string = the type of token, defining the hash type

API Module

The API module contains a generic response service to be used as the base for all API services that are meant to interact with the ETG .NET API. This generic response service contains CRUD functions pre-built to call our backend API and process the response in an easy-to-use way. By being able to specify the return object type for each service, the GenericResponseService will automatically convert all response data from the payload to the correct class model when it is returned.

Generic Response API

Implementation

Start by creating an empty Angular service.

Use the Angular generate command:

$ ng generate service <NAME_OF_SERVICE>

Or use the following code:

import { Injectable } from '@angular/core';

@Injectable({
	providedIn: 'root',
})
export class UserService {

	constructor() {

	}
}

Import the GenericResponseService at the top of your empty service. An HttpClient will be required for the GenericResponseService, so import that as well.

...

import { HttpClient } from "@angular/common/http";
import { GenericResponseService } from 'starter-ng-lib';

...

Create a class model to represent the objects being returned from the API that this service will be interacting with. For example, if using REST endpoints that manipulate user data ("API_URL/api/v1/Users"), create a User model that reflects that state of the models used on the backend.

Example:

export class User {
	id: number;
	email: string;
	name: string;
	tokens: UserTokens;
}

Extend your service with the GenericResponseService. Since the GenericResponseService is setup using generics, the response class type must be set when extending your service. Fill in 'CLASS_TYPE_HERE' with the name of the class model you created previously (example: User).

In the constructor, pass an injected HttpClient, API URL, and an endpoint string. In the User example, the API URL is "http://localhost:5000/api/v1" and the endpoint string would be "Users".

NOTE: The API URL can and should be set via an environment config file. In such a case, use the value from the config instead of "http://localhost:5000/api/v1".

...

@Injectable({
	providedIn: 'root',
})
export class UserService extends GenericResponseService<CLASS_TYPE_HERE> {

	constructor(
		httpClient: HttpClient
	) {
		super(httpClient, "http://localhost:5000/api/v1", "Users");
	}

	...
}

The full service is as follows:

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";

import { User } from "../models/user.model";
import { GenericResponseService } from 'starter-ng-lib';

@Injectable({
	providedIn: 'root',
})
export class UserService extends GenericResponseService<User> {

	constructor(
		httpClient: HttpClient
	) {
		super(httpClient, "http://localhost:5000/api/v1", "Users");
	}
}

Usage

With a service setup to use the GenericResponseService, it can be used simply by calling the CRUD functions included in the service.

In another component, import your new service and inject it into the component constructor (NOTE: Replace 'UserService' and '../service/user.service' with your service name and path respectively).

...

import { UserService } from '../service/user.service';

@Component({
	selector: 'component-selector',
	templateUrl: 'component-template.html',
	styleUrls: ['./component-styles.scss']
})
export class TestComponent {
	constructor(
		private userService: UserService
	) { }
  
	...
}

Call a function on the service based on the CRUD operation you wish to perform and interact with the response in the observables subscribe callback. For example, to retrieve a list of all users from our UserService:

this.userService.list().subscribe(
	(users) => {
		// Do something with the list of users here...
	},
	(err) => {
		// Handle error here...
	}
);

Alerts Module

The alerts module contains an AlertService to present simple toast messages and confirmation messages to users.

AlertService

Usage

To start using the AlertService, import it into the component you need it in and inject the service into your component constructor.

...

import { AlertService } from 'starter-ng-lib';

@Component({
	selector: 'component-selector',
	templateUrl: 'component-template.html',
	styleUrls: ['./component-styles.scss']
})
export class TestComponent {

	constructor(
		private alertService: AlertService
	) { }

	...

}

To use the AlertService to display an alert, call the various functions on the service as follows:

this.alertService.toast("This is a toast message!");

...

this.alertService.confirm("This is a confirmation", (result) => { ... });

API

The AlertService provides several functions for presenting toasts and confirmations. There are 4 types of alerts in each category: Info, Success, Warning, and Error.

Toast Alert

A toast alert will present a message at the top-right corner of the screen as a simple message that can be closed with no further action. By default a toast will remain for 5 seconds.

toast(message: string, title: string = "Info", timeout = undefined, customClass = "", position = undefined)

toast() simply presents a toast alert with a type of "info".

toastSuccess(message: string, title: string = "Success", timeout = undefined, customClass = "", position = undefined)

toastSuccess() presents a toast alert with a type of "success" and uses the color green to style the alert.

toastWarning(message: string, title: string = "Warning", timeout = undefined, customClass = "", position = undefined)

toastWarning() presents a toast alert with a type of "warning" and uses the color yellow to style the alert.

toastError(message: string, title: string = "Error", timeout = undefined, customClass = "", position = undefined)

toastError() presents a toast alert with a type of "error" and uses the color red to style the alert.

Confirmation Alert

A confirmation alert will present a message at the top-right corner of the screen with two buttons in it, one to cancel and one to confirm. A callback function is required to be passed to the confirm functions, that function will be called upon dismissing the confirmation alert. The context in which the confirmation was dismissed will be passed to the callback. A response of {value: true} means the confirm button was clicked, {dismiss: "cancel"} means the cancel button was clicked. By default, a confirmation alert has no timeout and will remain present until interacted with.

confirm(message: string, onDismiss: any, title: string = "Confirmation", confirmButtonText: string = "Confirm", cancelButtonText: string = "Cancel", timeout = undefined, customClass = "", position = undefined)

confirm() will display a confirmation alert with a type of "info". The two buttons default to "Cancel" and "Confirm".

confirmSuccess(message: string, onDismiss: any, title: string = "Confirmation", confirmButtonText: string = "Confirm", cancelButtonText: string = "Cancel", timeout = undefined, customClass = "", position = undefined)

confirmSuccess() will display a confirmation alert with a type of "success". The two buttons default to "Cancel" and "Confirm".

confirmWarning(message: string, onDismiss: any, title: string = "Confirmation", confirmButtonText: string = "Confirm", cancelButtonText: string = "Cancel", timeout = undefined, customClass = "", position = undefined)

confirmWarning() will display a confirmation alert with a type of "warning". The two buttons default to "Cancel" and "Confirm".

confirmError(message: string, onDismiss: any, title: string = "Confirmation", confirmButtonText: string = "Confirm", cancelButtonText: string = "Cancel", timeout = undefined, customClass = "", position = undefined)

confirmError() will display a confirmation alert with a type of "error". The two buttons default to "Cancel" and "Confirm".

Other Alerts
customAlert(config: any)

The customAlert() function will present an alert with no base settings, all alert settings must be provided in the passes-in config object. Options for the config can be viewed here (SweetAlert2).

Alert Positions

An alert's position can be set to any value in the AlertPosition enum. Changing an alert's position will cause it to display in a different section of the screen.

To set an alert position, import the Alertposition enum and send in a position option when triggering an alert as shown in the function definitions above. Possible position options are:

  • AlertPosition.TOP
  • AlertPosition.TOP_LEFT
  • AlertPosition.TOP_RIGHT
  • AlertPosition.CENTER
  • AlertPosition.CENTER_LEFT
  • AlertPosition.CENTER_RIGHT
  • AlertPosition.BOTTOM
  • AlertPosition.BOTTOM_LEFT
  • AlertPosition.BOTTOM_RIGHT
Alert Global Values

Some alert config values can be set globally to apply to all alerts. Global values can be retreieved and set by calling the corresponding global functions on the alert service. Possible global values and their setter functions are:

  • timeout | setGlobalTimeout(timeout: number)
  • customClass | setGlobalCustomClass(customClass: string)
  • position | setGlobalPosition(position: AlertPosition)
3.5.6

3 years ago

3.5.5

3 years ago

3.5.4

4 years ago

3.5.3

4 years ago

3.5.2

4 years ago

3.5.1

4 years ago

3.5.0

4 years ago

3.4.1

4 years ago

3.4.0

4 years ago

3.3.5

4 years ago

3.3.4

4 years ago

3.3.3

4 years ago

3.3.2

4 years ago

3.3.1

4 years ago

3.3.0

4 years ago

3.2.4

4 years ago

3.2.3

4 years ago

3.2.2

4 years ago

3.2.1

4 years ago

3.2.0

4 years ago

3.1.2

4 years ago

2.6.2

4 years ago

3.1.1

4 years ago

2.6.1

4 years ago

2.6.0

4 years ago

3.1.0

4 years ago

2.5.5

4 years ago

2.5.4

4 years ago

2.5.3

4 years ago

3.0.2

4 years ago

3.0.1

4 years ago

2.5.2

4 years ago

2.5.1

4 years ago

2.5.0

4 years ago

2.4.0

4 years ago

3.0.0

4 years ago

2.3.8

4 years ago

2.3.7

4 years ago

2.3.6

4 years ago

2.3.5

4 years ago

2.3.4

4 years ago

2.3.0

4 years ago

2.3.2

4 years ago

2.3.1

4 years ago

2.3.3

4 years ago

2.2.4

4 years ago

2.2.3

4 years ago

2.2.2

5 years ago

2.2.1

5 years ago

2.2.0

5 years ago

2.1.2

5 years ago

2.1.1

5 years ago

2.1.0

5 years ago

2.0.4

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.2.2

5 years ago

1.2.1

5 years ago

1.2.0

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.0

5 years ago