How can I be sure a constructor function only runs once? - rxjs

Is there any way for this code in the constructor of my service TranslatorService is calling just one time for all application or on demande, and not all time homecomponent is load ????
this.translations$ = translationsCollection.snapshotChanges().map(actions => {
return actions.map(a => {
...
})
translation class for my translate retrive from firestore ex:
{
"WELCOME": {
"FR": "bienvenue",
"GB": "Welcome"
}
}
export interface Translation {
[code: string]: TranslationInfo;
}
export interface TranslationInfo {
[language: string]: string;
}
my core module
import { NgModule } from '#angular/core';
import { AuthService } from './auth.service';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { TranslatorService } from '../services/translator.service';
#NgModule({
imports: [
AngularFireAuthModule,
AngularFirestoreModule
],
providers: [AuthService, TranslatorService]
})
export class CoreModule { }
injected in appmodule
#NgModule({
declarations: [
...
],
imports: [
...
CoreModule,
...
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
my translator service
#Injectable()
export class TranslatorService {
translationsCollection: AngularFirestoreCollection<Translation>;
translations$: Observable<any>;
public translations: Translation[];
constructor(private afs: AngularFirestore) {
var translationsCollection = this.afs.collection("translations");
this.translations$ = translationsCollection.snapshotChanges().map(actions => {
return actions.map(a => {
...
})
});
my component
export class HomeComponent implements OnInit {
translations$: Observable<any>;
constructor(private translator: TranslatorService) { }
ngOnInit() {
this.translations$ = this.translator.translations$;
}
my component view
<div *ngFor="let translation of translations$|async">
<pre>{{translation | json}}</pre>
</div>

Just use a singleton pattern: move the code to a static function and store its result in a static field. The constructor just calls the static function which will check the field before running its code:
export class TranslatorService {
translationsCollection: AngularFirestoreCollection<Translation>;
translations$: Observable<any>;
static tCollection : AngularFirestoreCollection<Translation>;
static t$: Observable<any>;
static initialize(afs: AngularFireStore) : void {
if (TranslatorService.tCollection == null) {
TranslatorService.tCollection = afs.collection("translations");
TranslatorService.t$ = TranslatorService.tCollection.snapshotChanges().map(actions => actions.map(a => ...));
}
}
public translations: Translation[];
constructor(private afs: AngularFirestore) {
TranslatorService.initialize(this.afs);
this.translations$ = TranslatorService.t$;
this.translationsCollection = TranslatorService.tCollection;
}
}

I have done something similar in one of my projects. You just need to move your translation code one level above. i.e.
Make a component called translation component which wraps all the components and put your logic in it. That way it will be loaded only once through the application life cycle.
You route config should then look something as follows:
const routes: Routes = [
{
path: '', component: LanguageComponent,
children: [
{ path: '', component: HomeComponent },
{ path: 'login', component: LoginComponent },
]
}
];
Basically all your application is wrapped into Language component.

Related

Tying to update PWA: swUpdate.isEnabled is true but not calling the subscribed method even when ngsw-config.json is altered

services/pwa.service.ts:
import { Injectable } from '#angular/core';
import { SwUpdate } from '#angular/service-worker';
import {Observable} from "rxjs/Observable";
import "rxjs/add/observable/interval";
#Injectable()
export class PwaService {
public promptEvent: any;
constructor(private swUpdate: SwUpdate) {
alert('swUpdate isEnabled:' + swUpdate.isEnabled);// => alerts true
if (swUpdate.isEnabled) {
Observable.interval(10)
.subscribe(() => swUpdate.checkForUpdate().then(() => alert('checking for swUpdate')));//<= Not triggered
}
}
public checkForUpdates(): void {
this.swUpdate.available.subscribe(event => this.promptUser());
}
private promptUser(): void {
alert('updating to new version');//<=Not triggered either
this.swUpdate.activateUpdate()
.then(() => document.location.reload());
}
}
services/index.ts:
providers: [
....
{ provide: SwUpdate, useClass: SwUpdate }
]
app.modules.ts:
imports: [
....
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }),
]
providers: [
...
PwaService,
]
app.component.ts:
import { PwaService } from './services/pwa.service';
....
constructor(public Pwa: PwaService) {
this.Pwa.checkForUpdates();
}
ngsw-config.json(just minor change from lazy to prefetch) to trigger update:
....
"installMode": "prefetch",
....
This worked for me on all devices:
export class PwaUpdateService {
updateSubscription;
constructor(public updates: SwUpdate) {
}
public checkForUpdates(): void {
this.updateSubscription = this.updates.available.subscribe(event => this.promptUser());
if (this.updates.isEnabled) {
// Required to enable updates on Windows and ios.
this.updates.activateUpdate();
interval(60 * 60 * 1000).subscribe(() => {
this.updates.checkForUpdate().then(() => {
// console.log('checking for updates');
});
});
}
// Important: on Safari (ios) Heroku doesn't auto redirect links to their https which allows the installation of the pwa like usual
// but it deactivates the swUpdate. So make sure to open your pwa on safari like so: https://example.com then (install/add to home)
}
promptUser(): void {
this.updates.activateUpdate().then(() => {
window.location.reload();
});
}
}

NgxLocalStorage Doesn't Retrieve Value

I'm learning how to use the Visual Studio 2017 SPA Template for Angular 2.
For this exercise I would just like my HomeComponent to display the name of the logged on user stored in local storage (NgxLocalStorage) after logging in on my AppLoginComponent. https://www.npmjs.com/package/ngx-localstorage
I've researched this issue and I believe I'm going down the right track but for some reason my HomeComponent doesn't see the key/value pair in localStorage. However, I can see it in Chrome's Developer Tools after I set it in login().
NgxLocalStorage has a method called get, not getItem but it appears to work the same way as getItem. Unfortunately it's not retrieving my value.
I'm pretty new to Angular 2, I'm sure I'm just missing something somewhere, please help.
I have imported NgxLocalStorageModule into NgModule in app.module.shared:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { RouterModule } from '#angular/router';
import { NgxLocalStorageModule } from 'ngx-localstorage';
import { AppComponent } from './components/app/app.component';
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { AppLoginComponent } from './components/applogin/applogin.component';
import { FacebookService, FacebookModule } from 'ngx-facebook/dist/esm/index';
#NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
AppLoginComponent
],
imports: [
CommonModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'applogin', component: AppLoginComponent },
{ path: '**', redirectTo: 'home' }
]),
FacebookModule.forRoot(),
NgxLocalStorageModule.forRoot()
],
providers: [FacebookService, NgxLocalStorageModule]
})
export class AppModuleShared {
}
In my HomeComponent I have:
import { Component } from '#angular/core';
import { LocalStorageService } from 'ngx-localstorage';
#Component({
selector: 'home',
templateUrl: './home.component.html'
})
export class HomeComponent {
currentUser: string;
constructor(private localStorage: LocalStorageService) {
this.currentUser = JSON.parse(localStorage.get('currentUser') || '');
}
}
In AppLoginComponent I have:
import { Component, NgZone } from '#angular/core';
import { FacebookService, InitParams, LoginResponse } from 'ngx-facebook/dist/esm/index';
import { LocalStorageService } from 'ngx-localstorage';
#Component({
selector: 'applogin',
templateUrl: './applogin.component.html'
})
export class AppLoginComponent {
public loggedIn = false;
name = "";
constructor(private _ngZone: NgZone, private fb: FacebookService, localStorage: LocalStorageService) {
let initParams: InitParams = {
appId: '123456789',
xfbml: true,
version: 'v2.8'
};
fb.init(initParams);
}
login() {
var self = this;
this.fb.login()
.then((res: LoginResponse) => {
if (res.authResponse) {
this.fb.api('/me')
.then((res: any) => {
self._ngZone.run(() => {
self.name = res.name;
self.loggedIn = true;
localStorage.setItem('currentUser', res.name);
});
});
} else {
alert('Not authorized.');
}
})
.catch();
}
I have created plunker where everything works. You press login button it will navigate to different component and show user in console the only difference from your code i used
this.localStorage.set('item', item);
and this.localStorage.get('item');
also in your code
this.fb.api('/me')
.then((res: any) => {
self._ngZone.run(() => {
self.name = res.name;
self.loggedIn = true;
localStorage.setItem('currentUser', res.name);
});
});
you can't use like this services outside constructor and don't use self you need to add 'this'. and in you constructor prefix localStorage with private
and do initialization better in OnInit hook.
import { Component, NgZone, OnInit } from '#angular/core';
import { FacebookService, InitParams, LoginResponse } from 'ngx-facebook/dist/esm/index';
import { LocalStorageService } from 'ngx-localstorage';
#Component({
selector: 'applogin',
templateUrl: './applogin.component.html'
})
export class AppLoginComponent implements OnInit {
public loggedIn = false;
name = "";
constructor(private _ngZone: NgZone, private fb: FacebookService, private localStorage: LocalStorageService) {
}
ngOnInit() {
let initParams: InitParams = {
appId: '123456789',
xfbml: true,
version: 'v2.8'
};
fb.init(initParams);
}
login() {
this.fb.login()
.then((res: LoginResponse) => {
if (res.authResponse) {
this.fb.api('/me')
.then((res: any) => {
this._ngZone.run(() => {
this.name = res.name;
this.loggedIn = true;
this.localStorage.set('currentUser', res.name);
});
});
} else {
alert('Not authorized.');
}
})
.catch();
}
and in app.module.shared.ts remove this line
providers: [FacebookService, NgxLocalStorageModule]
cause forRoot is importing them already. should be like this
#NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
AppLoginComponent
],
imports: [
CommonModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'applogin', component: AppLoginComponent },
{ path: '**', redirectTo: 'home' }
]),
FacebookModule.forRoot(),
NgxLocalStorageModule.forRoot()
]
})
export class AppModuleShared {
}
and the last
import { FacebookService, FacebookModule } from 'ngx-facebook/dist/esm/index';
try to use import without dist
import { FacebookModule } from 'ngx-facebook';
The input has to be a string. You can put in some mock data like
localStorage.setItem('currentUser', 'TrevorBrooks');
and retrieve it via get to be sure there is a item saved. And check what data type you are sending. Is it a user object or is it just the name?
Greetings
You should use NgOnInit, is the best approach for your problem than using the constructor since the constructor is for initialization, dependency injection among others.. so, what could be happening is that the data is not yet available by the time you request it. Besides in the npmjs.com page they clearly add an example using ngOnInit so i guess they saw this issue coming.
In your components, do import { .., OnInit, .. } from '#angular/core';
`
so you'd have something like:
import { Component, NgZone, OnInit } from '#angular/core';
and in your component export class:
export class AppLoginComponent implements OnInit{
ngOnInit() {
//write your code here
}
1.Make sure you have been installed the local storage module from npm
npm install --save angular2-localstorage
2.Import the WebStorageModule in your app module:
import {Component} from "angular2/core";
import {WebStorageModule, LocalStorageService} from "angular2-localstorage";
#NgModule({
import: [WebStorageModule]
#Component({
providers: [LocalStorageService]
})
export class AppModule {}
2.Use the LocalStorage decorator
import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";
class MySuperComponent {
#LocalStorage() public lastSearchQuery:Object = {};
#LocalStorage('differentLocalStorageKey') public lastSearchQuery:Object = {};
}
Example
#Component({
selector: 'app-login',
template: `
<form>
<div>
<input type="text" [(ngModel)]="username" placeholder="Username" />
<input type="password" [(ngModel)]="password" placeholder="Password" />
</div>
<input type="checkbox" [(ngModel)]="rememberMe" /> Keep me logged in
<button type="submit">Login</button>
</form>
`
})
class AppLoginComponent {
//here happens the magic. `username` is always restored from the localstorage when you reload the site
#LocalStorage() public username:string = '';
public password:string;
//here happens the magic. `rememberMe` is always restored from the localstorage when you reload the site
#LocalStorage() public rememberMe:boolean = false;
}
View
#Component({
selector: 'admin-menu',
template: `
<div *ngFor="#menuItem of menuItems() | mapToIterable; #i = index">
<h2 (click)="hiddenMenuItems[i] = !!!hiddenMenuItems[i]">
{{i}}: {{category.label}}
</h2>
<div style="padding-left: 15px;" [hidden]="hiddenMenuItems[i]">
<a href>Some sub menu item 1</a>
<a href>Some sub menu item 2</a>
<a href>Some sub menu item 3</a>
</div>
</div>
`
})
class AdminMenuComponent {
public menuItems = [{title: 'Menu1'}, {title: 'Menu2'}, {title: 'Menu3'}];
//here happens the magic. `hiddenMenuItems` is always restored from the localstorage when you reload the site
#LocalStorage() public hiddenMenuItems:Array<boolean> = [];
//here happens the magic. `profile` is always restored from the sessionStorage when you reload the site from the current tab/browser. This is perfect for more sensitive information that shouldn't stay once the user closes the browser.
#SessionStorage() public profile:any = {};
}
For more Clarification refer this link link

Angular 2 unit test for component

I am using ng2 with webpack 2.
I cant figure out how to test component functions
Here is my component
import { Component, OnInit } from '#angular/core';
import { GlobalDataService } from '../global.service';
import { Router } from '#angular/router';
#Component({
selector: 'login',
templateUrl: './login.component.html'
})
export class LoginComponent {
constructor(private gd: GlobalDataService, private router: Router) { }
login(): void {
this.gd.shareObj['role'] = 'admin';
this.router.navigateByUrl('/login');
}
}
I would like to test login() function and see, if this.gd.shareObj['role'] = 'admin'; is truly set as admin.
What could .spec.ts file look like?
I would do it as follows:
class RouterStub {
navigateByUrl(url: String) { return url; }
}
class GlobalDataServiceStub {
shareObj: any = {};
}
describe('LoginComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [LoginComponent],
providers: [
{ provide: GlobalDataService, useClass: GlobalDataServiceStub },
{ provide: Router, useClass: RouterStub }
]
});
fixture = TestBed.createComponent(LoginComponent);
comp = fixture.componentInstance;
});
it('should set role to admin',
inject([GlobalDataService], (gd: GlobalDataService) => {
comp.login();
expect(gd.shareObj['role']).toBe('admin');
})
);
});
Plunker Example

Passing an additional value to custom validator in Angular2?

I have a validator that checks if a users email address is unique, to do this I need to also pass in the users id so that it doesn't include itself in the unique checks. What is the best way to achieve this?
From what I can tell the validator only has access to the control value. I'm hooking up my validator like this:
<input #emailAddress="ngForm" type="text" [(ngModel)]="user.emailAddress" ngControl="emailAddress" required userExists />
Currently the only way I've been able to achieve it is by setting a static value on the validator, which is not ideal! Here's my full code for the validator:
import { NG_ASYNC_VALIDATORS, Control } from '#angular/common';
import { Directive, provide, forwardRef, Attribute } from '#angular/core';
import { UserService } from './user.service';
import { User } from './user.model';
interface ValidationResult {
[key: string]: boolean;
}
#Directive({
selector: '[userExists][ngModel]',
providers: [
provide(NG_ASYNC_VALIDATORS, {
useExisting: forwardRef(() => UserExistsValidator),
multi: true
})
]
})
export class UserExistsValidator {
public static user: User;
constructor(private _userService: UserService) { }
validate(control: Control): Promise<ValidationResult> {
return new Promise((resolve, reject) => {
this._userService.exists(control.value, UserExistsValidator.user.id).subscribe(
(response: any) => {
if (response.exists)
return resolve({ userExists: { valid: false } });
else
return resolve(null);
},
(error: any) => { console.log(error); }
)
});
}
}
I would use a shared service
#Injectable()
class ValidatorParam {
value:string; // could also be an observable
}
#Directive({
selector: '[userExists][ngModel]',
providers: [
{ provide: NG_ASYNC_VALIDATORS,
useExisting: forwardRef(() => UserExistsValidator),
multi: true
})
]
})
export class UserExistsValidator {
public static user: User;
constructor(private _userService: UserService, private _param:ValidatorParam) { }
validate(control: Control): Promise<ValidationResult> {
return new Promise((resolve, reject) => {
this._param.... // don't know what you want to do with it
this._userService.exists(control.value, UserExistsValidator.user.id).subscribe(
(response: any) => {
if (response.exists)
return resolve({ userExists: { valid: false } });
else
return resolve(null);
},
(error: any) => { console.log(error); }
)
});
}
}
#Component({
selector: '...',
providers: [ValidatorParam],
template: `
<input #emailAddress="ngForm" type="text" [(ngModel)]="user.emailAddress" ngControl="emailAddress" required userExists />
`})
export class MyComponent {
constructor(private _validatorParam:ValidatorParam) {
this._validatorParam.value = xxx;
}
}
This way you can only have one service per component. If you have several input elements in this component, then they need to share the service.
Caution: not tried myself.

Angular2 template driven async validator

I have a problem with defining asynchrous validator in template driven form.
Currently i have this input:
<input type="text" ngControl="email" [(ngModel)]="model.applicant.contact.email" #email="ngForm" required asyncEmailValidator>
with validator selector asyncEmailValidator which is pointing to this class:
import {provide} from "angular2/core";
import {Directive} from "angular2/core";
import {NG_VALIDATORS} from "angular2/common";
import {Validator} from "angular2/common";
import {Control} from "angular2/common";
import {AccountService} from "../services/account.service";
#Directive({
selector: '[asyncEmailValidator]',
providers: [provide(NG_VALIDATORS, {useExisting: EmailValidator, multi: true}), AccountService]
})
export class EmailValidator implements Validator {
//https://angular.io/docs/ts/latest/api/common/Validator-interface.html
constructor(private accountService:AccountService) {
}
validate(c:Control):{[key: string]: any} {
let EMAIL_REGEXP = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*#([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
if (!EMAIL_REGEXP.test(c.value)) {
return {validateEmail: {valid: false}};
}
return null;
/*return new Promise(resolve =>
this.accountService.getUserNames(c.value).subscribe(res => {
if (res == true) {
resolve(null);
}
else {
resolve({validateEmailTaken: {valid: false}});
}
}));*/
}
}
Email regex part is working as expected and form is being validated successfuly if regex is matching. But after that I want to check if e-mail is not already in use, so im creating promise for my accountService. But this doesn't work at all and form is in failed state all the time.
I've read about model driven forms and using FormBuilder as below:
constructor(builder: FormBuilder) {
this.email = new Control('',
Validators.compose([Validators.required, CustomValidators.emailFormat]), CustomValidators.duplicated
);
}
Which have async validators defined in third parameter of Control() But this is not my case because im using diffrent approach.
So, my question is: is it possible to create async validator using template driven forms?
You could try to register the provider of your async validator with the NG_ASYNC_VALIDATORS key and not the NG_VALIDATORS one (only for synchronous validators):
#Directive({
selector: '[asyncEmailValidator]',
providers: [
provide(NG_ASYNC_VALIDATORS, { // <------------
useExisting: EmailValidator, multi: true
}),
AccountService
]
})
export class EmailValidator implements Validator {
constructor(private accountService:AccountService) {
}
validate(c:Control) {
return new Promise(resolve =>
this.accountService.getUserNames(c.value).subscribe(res => {
if (res == true) {
resolve(null);
}
else {
resolve({validateEmailTaken: {valid: false}});
}
}));
}
}
See this doc on the angular.io website:
https://angular.io/docs/ts/latest/api/forms/index/NG_ASYNC_VALIDATORS-let.html
worth noting that the syntax has changed since then, now i am using angular 4, and here below a rewrite:
import { Directive, forwardRef } from '#angular/core';
import { AbstractControl, Validator, NG_ASYNC_VALIDATORS } from '#angular/forms';
import { AccountService } from 'account.service';
#Directive({
selector: '[asyncEmailValidator]',
providers: [
{
provide: NG_ASYNC_VALIDATORS,
useExisting: forwardRef(() => EmailValidatorDirective), multi: true
},
]
})
export class EmailValidatorDirective implements Validator {
constructor(private _accountService: AccountService) {
}
validate(c: AbstractControl) {
return new Promise(resolve =>
this._accountService.isEmailExists(c.value).subscribe(res => {
if (res == true) {
resolve({ validateEmailTaken: { valid: false } });
}
else {
resolve(null);
}
}));
}
}
I am able to correctly call validate custom validators using user service. One problem i was getting was that, I kept my custom validator inside Validators.compose(). After taking out of the compose function everything works.
import { Directive } from '#angular/core';
import { AsyncValidator, AbstractControl, ValidationErrors, NG_ASYNC_VALIDATORS, AsyncValidatorFn } from '#angular/forms';
import { Observable } from 'rxjs';
import { UserService } from '../Services/user.service';
import { map } from 'rxjs/operators';
export function UniqueUsernameValidator(userService: UserService): AsyncValidatorFn {
return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
const q = new Promise((resolve, reject) => {
setTimeout(() => {
userService.isUsernameTaken(control.value).subscribe((data: any) => {
// console.log('top: ' + data + ' type: ' + typeof data);
if (data === false) {
resolve(null);
} else {
resolve({
usernameTaken: {
valid: true
}
});
}
}, () => {
resolve({
usernameTaken: {
valid: false
}
});
});
}, 1000);
});
return q;
};
}
#Directive({
selector: '[appUniqueUsername]',
providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: UniqueUsernameValidatorDirective, multi: true }, UserService]
})
export class UniqueUsernameValidatorDirective implements AsyncValidator {
constructor(private userService: UserService) { }
validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
return UniqueUsernameValidator(this.userService)(control);
}
}

Resources