javascript - Is there a better way to access Angular's components private properties? - TagMerge
3Is there a better way to access Angular's components private properties?Is there a better way to access Angular's components private properties?

Is there a better way to access Angular's components private properties?

Asked 10 months ago
0
3 answers

In v12 and below you could inject and then use ComponentFactoryResolver (docs) to get the components ComponentFactory (docs) which gives public access to those properties:

const factory: ComponentFactory = componentFactoryResolver.resolveComponentFactory(TestComponent);
console.log(factory.selector);
console.log(factory.inputs);
console.log(factory.outputs);

Although this method is now marked as deprecated in v13.

Source: link

0

We can use a basic set of commands to generate our components but every command has its own options. For example, if we want to generate a component we would type:
ng g component example_component
When we add names to our classes, we should use upper camel case style with the added suffix that represents the type of our file:
export class DatepickerDirective
export class HomeComponent
export class RepositoryService
If we want to create a contract for our class we should always use interfaces. By using them we can force the class to implement functions and properties declared inside the interface. Let’s take for example OnInit interface and its implementation:
export interface OnInit {
    ngOnInit(): void;
}
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    
}
export interface User {
    name: string;
    age: number;
    address: string;
}

Source: link

0

We can use the jwt-decode package for decoding JWT tokens. In this service, functions for getting user claim values like username and email ID have been included. A function has also been added for checking token expiration in this service.
import { Injectable } from '@angular/core';
import * as jwt_decode from 'jwt-decode';

@Injectable()
export class JWTTokenService {

    jwtToken: string;
    decodedToken: { [key: string]: string };

    constructor() {
    }

    setToken(token: string) {
      if (token) {
        this.jwtToken = token;
      }
    }

    decodeToken() {
      if (this.jwtToken) {
      this.decodedToken = jwt_decode(this.jwtToken);
      }
    }

    getDecodeToken() {
      return jwt_decode(this.jwtToken);
    }

    getUser() {
      this.decodeToken();
      return this.decodedToken ? this.decodedToken.displayname : null;
    }

    getEmailId() {
      this.decodeToken();
      return this.decodedToken ? this.decodedToken.email : null;
    }

    getExpiryTime() {
      this.decodeToken();
      return this.decodedToken ? this.decodedToken.exp : null;
    }

    isTokenExpired(): boolean {
      const expiryTime: number = this.getExpiryTime();
      if (expiryTime) {
        return ((1000 * expiryTime) - (new Date()).getTime()) < 5000;
      } else {
        return false;
      }
    }
}
Create an Angular service file AppCookieService and inject it in the application module.Include the get, set, and remove functions to perform cookie operations.Include the functionality to automatically add the cookie on initialization of the service.
import { Inject, Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root',
  })
export class AppCookieService {
    private cookieStore = {};

    constructor() {
        this.parseCookies(document.cookie);
    }

    public parseCookies(cookies = document.cookie) {
        this.cookieStore = {};
        if (!!cookies === false) { return; }
        const cookiesArr = cookies.split(';');
        for (const cookie of cookiesArr) {
            const cookieArr = cookie.split('=');
            this.cookieStore[cookieArr[0].trim()] = cookieArr[1];
        }
    }

    get(key: string) {
        this.parseCookies();
        return !!this.cookieStore[key] ? this.cookieStore[key] : null;
    }

    remove(key: string) {
      document.cookie = `${key} = ; expires=Thu, 1 jan 1990 12:00:00 UTC; path=/`;
    }

    set(key: string, value: string) {
        document.cookie = key + '=' + (value || '');
    }
}
Create an Angular service file LocalStorageService and inject it in the application module.In this basic local storage, add get, set, and remove functions for performing the operations.
import { Injectable } from '@angular/core';

@Injectable()
export class LocalStorageService {

    set(key: string, value: string) {
        localStorage.setItem(key, value);
    }

    get(key: string) {
        return localStorage.getItem(key);
    }

    remove(key: string) {
        localStorage.removeItem(key);
    }
}
Before diving into this topic, we have to understand the routing guard canActivate.
{
    path: 'app',
    component: AppComponent,
    canActivate: [AuthorizeGuard]
}
The guard service in the sample code below checks whether the user is logged in. If the user is logged in, then it checks whether the token is expired. If both cases are satisfied, then the routing process will be successful. Otherwise, it will request the login service to get a new token or redirect the user to a custom login or access denied page.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs'; 
import { JWTTokenService } from './jwt-token.service';
import { LocalStorageService } from './storage.service';
import { LoginService } from './login.service';

@Injectable({
  providedIn: 'root'
})
export class AuthorizeGuard implements CanActivate {
  constructor(private loginService: LoginService,
              private authStorageService: LocalStorageService,
              private jwtService: JWTTokenService) {
  }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable | Promise | boolean {
      if (this.jwtService.getUser()) {
          if (this.jwtService.isTokenExpired()) {
            // Should Redirect Sig-In Page
          } else {
            return true;
          }
      } else {
        return new Promise((resolve) => {
          this.loginService.signIncallBack().then((e) => {
             resolve(true);
          }).catch((e) => {
            // Should Redirect Sign-In Page
          });
        });
      }
  }
}

Source: link

Recent Questions on javascript

    Programming Languages