Skip to content

Instantly share code, notes, and snippets.

View splincode's full-sized avatar
💬
Typing...

Maksim Ivanov splincode

💬
Typing...
View GitHub Profile
@State<AuthModel>({
name: 'auth',
defaults: {
token: null,
exp: null
}
})
@Injectable()
export class AuthState {
@StateRepository()
@State<AuthModel>({
name: 'auth',
defaults: {
token: null,
exp: null
}
})
@Injectable()
export class AuthState extends NgxsDataRepository<AuthModel> { }
@Injectable()
export class TokenInterceptor {
constructor(private authInfo: AuthState) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.authInfo.snapshot.token) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${this.authInfo.snapshot.token}`,
},
@Injectable()
export class TokenInterceptor {
constructor(private store: Store) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token: string | null = this.store.selectSnapshot(AuthState.token);
if (token) {
req = req.clone({
setHeaders: {
interface UserModel {
id: number | null;
username: string | null;
age: number | null;
}
@StateRepository()
@State<UserModel>({
name: 'userInfo',
defaults: {
interface UserModel {
id: number | null;
username: string | null;
age: number | null;
}
export class UserSetAction {
public static type: string = '[UserSetAction]: action';
constructor(public payload: UserModel) {}
}
// ...
@Component({
selector: 'counter',
template: `
value: {{ (counter$ | async).value }} <br>
<button (click)="increment()">increment</button>
`
})
export class CounterComponent {
import { Injectable } from '@angular/core';
import { State } from '@ngxs/store';
interface CountModel {
value: number;
}
export class IncrementAction {
public static type: string = '[Increment]';
constructor(public value: number) {}
import { Injectable } from '@angular/core';
import { Store } from './store';
interface CountModel {
value: number;
}
@Injectable()
export class CounterStore extends Store<CountModel> {
private initialCount: CountModel = { value: 0 };
import { BehaviorSubject, Observable } from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable()
export abstract class Store<T> {
private _state$: BehaviorSubject<T>;
protected constructor(defaults: T) {
this.state$ = new BehaviorSubject(defaults);
}