Showing posts with label Angular. Show all posts
Showing posts with label Angular. Show all posts

Sunday, March 15, 2020

Angular Development Quick tips

1. create services in specific folder (like in the Shared folder)

ng g s Shared/myservice

2. use dry run mode (-d) to check the outcome before really execute the command

ng g s shared/myservice -d 

3. use --flat to skip generating the folder for the component

ng g c mycomponenet --flat

4. use $ suffix to indicate the variable is an observable

let keyup$=Observable.fromEvent(this.inputField.nativeElement, 'keyup');

5. use hashtag # to uniquely identify the elements in the template

<input type="text" #myInputField >

6. Angular provide a special class ElementRef to directly access the element.

7.  use @ViewChild to find the element in the template

@ViewChild('myInputField') myInput : ElementRef;

let inputValue=this.myInput.nativeElement;

more to come..................

Saturday, March 14, 2020

How to get the name of the route the user try to navigate on canAcitvate method?

when we want to know what component the use try to access with AuthGuard enable, it is quit simple

we can put a console.log in the canActivate Method, to monitor the ActivateRouteSnapshot in Angular 9


console.log("the name of route: " + destination.routeConfig.component.name);
 

in Angular 6

you can access it from route.component.name

here is the sample code


import { Injectable } from "@angular/core";
import { CanActivate, Router, ActivatedRouteSnapshot,  
RouterStateSnapshot } from '@angular/router';

@Injectable()
export class longinGuard implements CanActivate{
    constructor(private router: Router){

    }
    canActivate(destination: ActivatedRouteSnapshot, state: RouterStateSnapshot){
        console.log("the name of route navigate to: " +
  destination.routeConfig.component.name);
  
    }
}

Tuesday, February 11, 2020

How to solve "ERROR TypeError: Cannot read property 'subscribe' of undefined" in angular development?

after i completed my sample angular application, i ran it the result did show in the page.

however there was an error message in the console in the development tool.

"ERROR TypeError: Cannot read property 'subscribe' of undefined" 

core.js:5828 ERROR TypeError: Cannot read property 'subscribe' of undefined
    at AppComponent.ngOnInit (app.component.ts:24)
    at callHook (core.js:3892)
    at callHooks (core.js:3856)
    at executeInitAndCheckHooks (core.js:3797)
    at refreshView (core.js:11706)
    at renderComponentOrTemplate (core.js:11814)
    at tickRootContext (core.js:13290)
    at detectChangesInRootView (core.js:13324)
    at RootViewRef.detectChanges (core.js:15004)

    at ApplicationRef.tick (core.js:42192)


THE ROOT CAUSE OF THIS ERROR IS StocksService had been subscribed twice, one in the AppComponent, another one is in the DashBoard Component. after i comment out the code in the AppComponent. the error is gone. it is also a bad idea to call the service the AppComponent. since i had the routing enable.


export class AppComponent {
  stocks: Array<StockInterface>;
  symbols: Array<string>;
  constructor(private service: StocksService){
    //  this.service.load(['APPL']).subscribe(stocks=>{
    //    this.stocks=stocks;
    //  }
      // );
   }

   ngOnInit(){
     this.service.load(this.symbols).subscribe(stocks=>{
       this.stocks=stocks;
     });
   }
}



export class DashboardComponent implements OnInit {
  stocks: Array<StockInterface>;
  symbols: Array<string>;
  constructor(private service: StocksService) {
      this.symbols=service.get();
   }
  ngOnInit(): void {
    this.service.load(this.symbols).subscribe(
      stocks=>this.stocks=stocks);
  }
}

Monday, January 20, 2020

how to fix "error NG8001: "your selector'' is not a known element" in Angular Development

after i run npm build to compile my angular project

i got the following error

C:\DanAngular\triathlon-app>ng build

ERROR in src/app/results/results/results.component.html:2:1 - error NG8001: 'results-list' is not a known element:
1. If 'results-list' is an Angular component, then verify that it is part of this module.
2. If 'results-list' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

2 <results-list (selected)=showDetails($event)>Loading athelete list ...</results-list>


when i go inside my project and locate the results-list.component.ts

the selector had been defined as app-results-list

@Component({
  selector: 'app-results-list',
  templateUrl: './results-list.component.html',
  styleUrls: ['./results-list.component.scss']
})
export class ResultsListComponent implements OnInit {
  athletes: Athlete[];
  timingPoints: TimingPoint[];
  @Output() selected=new EventEmitter<Athlete>();

  constructor(private athleteService: AthleteServiceService) { }



 <results-list (selected)=showDetails($event)>Loading athelete list ...</results-list>

should use app-results-list as the selector.

 <app-results-list (selected)=showDetails($event)>Loading athelete list ...</app-results-list>



how to fix "Property 'map' does not exist on type 'Observable'" in Angular Development

1. first install the latest ReactJS compact package

     npm install --save rxjs-compat@6

2. reference to the rxjs/rx

import 'rxjs/Rx';





Angular Development Quick Tips 2


1. Import {Http, Response} from '@angular/http' will cause a not error if you do not expressively install the libary.

npm install @angular/http@latest.

for the latest angular/CLI, the library had been moved to @angular/common/http.

we should use the correct path

Import {Http, Response} from '@angular/common/http'

2. how to generate a component inside the specific folder without a folder

npm g c specifiFolder/mycomponent --flat -d

the  --flat instructed the npm command to generate a component without a folder.

-d will force a dry run and show you the output in the windows only. you can verify the output before generating them.



 



Sunday, January 5, 2020

Angular Development Quick Tip 1

1. Augury is the great chrome add in to visualize data for Angular Development

you can give it here

https://chrome.google.com/webstore/detail/augury/elgalmkoelokbchhkhacckoklkejnhcd/related?hl=en










2. run ng generate command with -d flag to verify the location, name etc before it really create them.
 since dry run mode will not make any change in the current solution

ng generate service myService -d








C:\DanAngular\dan-app>ng generate service myService -d
CREATE src/app/my-service.service.spec.ts (349 bytes)
CREATE src/app/my-service.service.ts (138 bytes)

NOTE: The "dryRun" flag means no changes were made.

from the above output, I should be able to find that i do not need to use myService as the service name

i tweak my command to ng generate serivce my -d








C:\DanAngular\dan-app>ng generate service my -d
CREATE src/app/my.service.spec.ts (313 bytes)
CREATE src/app/my.service.ts (131 bytes)

NOTE: The "dryRun" flag means no changes were made.





Tuesday, June 18, 2019

how to integrate Microsoft Azure Authetication in angular SPA with adal.js?

it is very common to use Azure authentication to authenticate the user access in the SPA.

it is not hard to setup a sample app running if we follow the steps below.

1. install anulgar/CLI

    npm i @angular/CLI 


2. install angular-adal

    npm i angular-adal

3 . install type definition of adal

    npm i @type/adal --save

4. install type script libary

    npm i tslib

5. finally install the microsoft-adal-angular6 package

    npm i microsoft-adal-angular6 
 
6. now you can following the example from this link

https://www.npmjs.com/package/microsoft-adal-angular6


@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
MsAdalAngular6Module.forRoot({
tenant: 'tennat guid id from azure active directory',
clientId: 'the app id registered in the cloud',
// redirectUri: window.location.origin,
// endpoints: {
// "https://localhost/Api/": "xxx-bae6-4760-b434-xxx"
// },
navigateToLoginRequestUrl: false,
cacheLocation: 'localStorage',
})
],
providers: [AuthenticationGuard],
bootstrap: [AppComponent]
})


here is the screen shot showing the path to get the Tenant ID
 
 

  
you can find your app client ID from this image
 
 



actually we can find both tenant ID and client ID after you click on the MyADAuthApp 
in the app registrations section.
 
 
 
 
 
 now we can launch the SPA with ng-serve to run the app, and type http://localhost:4200
 
 it will direct to the azure authentication login screen