0% found this document useful (0 votes)
13 views

Angular 17 Notes

The document provides an overview of Angular, covering its framework features, including single-page applications (SPA), lazy loading, and the MVC architecture. It discusses various Angular concepts such as decorators, data binding, directives, services, routing, and observables, along with their implementation and usage in components. Additionally, it highlights the importance of guards for route protection and the use of dependency injection for service management.

Uploaded by

mina.hany01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Angular 17 Notes

The document provides an overview of Angular, covering its framework features, including single-page applications (SPA), lazy loading, and the MVC architecture. It discusses various Angular concepts such as decorators, data binding, directives, services, routing, and observables, along with their implementation and usage in components. Additionally, it highlights the importance of guards for route protection and the use of dependency injection for service management.

Uploaded by

mina.hany01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

===========Lec1

-> Angular is a framework

-> SPA: single page application

-> Lazy-Loading( By default, NgModules are eagerly loaded. This means that as soon as the
application loads, so do all the NgModules, whether they are immediately necessary or not. For
large applications with lots of routes, consider lazy loading —a design pattern that loads
NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps
decrease load times.,some of components loaded when the user need it )

-> install node js , angular/cli (npm i @angular/cli -g)

-> angular use MVC architecture pattern

-> before angular 17 : project consists of modules

-> angular 17 : standalone project

-> ng new projName

-> ng serve --o

 Decorator design pattern

Design Pattern — Decorator in Angular | by Bulicka Ola | Design Pattern — Decorator in Angular
| Medium

->ng g c componentName

-> component selector : Selectors • Angular

-> npm i bootstrap

 interpolation {{data from ts to html}}

property binding

*ngFor
===========Lec2

 SSR : server side rendering

1-Binding

1-Interpolation (from ts to html)

2-Proberty binding(from ts to html)

3-event binding (from html to ts)

-> template reference variable


->casting from string to int using(+varName,parseInt(varName),Number(varName))

4- Two-way binding (banana in box [()] )


->from view(html) to controller(ts) then from ts to html
->use ngModel (import formsModule)
5- class binding (from controller to view)
->to add or remove a class according to a condition

6- style binding(from controller to view)


->to add or remove a css style according to a condition

2- Directives

built in directives:

Directives • Overview • Angular

1-component directive (the tag used to display the component using component selector)

2-structural directive (ngFor,ngIf,ngSwitch)

->use trackBy with ngFor: To reduce the number of calls your application makes to the
server by tracking changes to an item list. With the *ngFor trackBy property, Angular
can change and re-render only those items that have changed, rather than reloading the
entire list of items.
->note: we cant use multiple template binding on one element(this mean we cant use
two structural directives on the element)
-so use ng-container tag (this tag doesn’t appear )

->ng-template tag (content inside it doesn’t appear unless using reference(#))

->ngSwitch

3-Attribute directive

->NgClass (difference between NgClass and class binding that in NgClass we can applay
another class if the condition is false)

->NgStyle (at NgStyle we can use many properties but style binding use one property)

->NgModel (two-way binding)

custom directives:
============Lec3

1-control flow

Control flow • Angular

2- custom directives
 Note: initially the background color will take the default color red not gray

In Angular, decorators are functions that allow you to modify the behavior of classes,
methods, properties, or parameters. They provide a way to add metadata or apply
transformations to code elements, making it easier to define and configure various
application elements. Decorators are extensively used in Angular to define
components, services, directives, pipes, modules, and more.

Types of Decorators in Angular


Angular provides several built-in decorators, which can be classified into four main
types:
1. Class Decorators: Applied to classes to modify their behavior or metadata.
Examples include @Component , @Directive , and @NgModule .
2. Property Decorators: Applied to class properties to modify them. Examples
include @Input and @Output .
3. Method Decorators: Applied to class methods to modify their behavior or add
additional functionalities. Examples include @HostListener .
4. Parameter Decorators: Applied to parameters inside class constructors to
provide additional information. Examples include @Inject .
3-Pipes:

 Directive vs pipe: Directives for tags , but pipes for values


 Function vs pipe : function for its component only, pipes can be used at any
component
 Pipes • Angular

4- component life cycle:

Lifecycle • Angular

-> lifecycle hooks (some of methods)

-> there are four phases for the component(Creation, ChangeDetection, Rendering,
Destruction)

 The directive should implement OnChanges interface to use ngOnChanges: now


the default color will be the input color not the red
5- components interaction:

->if components are unrelated use services

-> if they are related(parent component and child component) use input and output
decorators

->to send data from parent to child use input decorator , the parent send data to child in
the child selector
-> to send from child to parent use event: child is the publisher of the event and parent
is listener

-> to publish event first define event using EventEmitter(generic interface) and the
output decorator, then fire the event using emit function

->then the parent will listen in the child selector


===============>Lec4

1-viewChild decorator function:

->note: when use template reference variable we can use its tag at view(html) in
another tag ,but we can not use it in ts

->to be able to use the tag in ts we use ViewChild decorator function

->non null assertion operator (!): use it if we don’t want to give initial value for the
member

->myInp is a variable that will have a tag so its type is ElementRef

->now use @ViewChild("temp ref variable") decorator function to tell myInp variable
which tag it will have after the view is loaded

->we use ngAfterViewInit life cycle hock to use inside it the tag to insure that the
view has loaded and we get the tag (the component should implement AfterViewInit
interface), and we use nativeElement.value to change the value of the tag
->first use of @ViewChild is to get a tag from view into ts by using its template ref
variable

->Also we use it if the component has child component so we use ViewChild by using
child component name

->What is the deference between using ViewChild decorator to use variable from child
into parent , and using EventEmitter and @output decorator:

-when we use ViewChild if the variable inside child changed the parent will not feel
the change in the variable, but using event and output decorator make parent feel
the changes
2-Services:

->At components interactions : if components are unrelated use services

->service is a class ,we use it if there is variables or methods that will be used in many
components

->services use singleton design pattern: this mean if many components make
instances from this service if one component make change in any variable so each
components will feel this change as they have the same instance

-> ng g service serviceName

->the class of the service has @Injectable decorator function

->dependency injection design pattern:

->class B want to use class A:

-if we make object or instance from A in B let obj=new A()) , if we make


changes in A we should change it in class B and that doesn’t match solid
principles

-so we have to use dependency injection design pattern : to do that we will


pass an instance of A as parameter when we make an instance of B

Let obj=new B(new A(…),…)

-so if there is any change in class A we will modify the object of B that has
instance of A as parameter , and we will not modify class B
-so we have injected object from class A inside constructor of class B

->Now we have StaticProductsService and we want to use it inside products


component:

- make private member inside the constructor of products component , this


member of type StaticProductsService and will have the first parameter when
we make obj of products

-when we make obj of products ,Angular will make instance of


StaticProductsService and pass it to the construct , so we don’t have to
make the instance of the service

->providedIn: ‘root’ (this mean we can inject and use this service inside any component
in the project)
-as service use singleton design pattern so all components use this service will have
the same instance ,but if we want any component make its own instance of the
service we make providers array in the component decorator and pass to it the service
name
3-Routing:

->it’s the navigation from component to another one

->Angular has Router Module

->inside app.routes.ts file we write paths {path: ‘pathName’,component:compName}

->if the path is …/Home the home component displayed

->but first we have to use router-outlet directive


->first match win :angular use this principle

-so when we want to make a path matches any path the user write instead Home,
Products or About paths we write path: ‘**’ and it navigate to notFound page

-if we write this path first one , if the user write Home, Products or About paths it will
navigate to notFound page not there pages because ** matches any path and the first
match wins

->router-link directive:

-we should import RouterLink


->routerLinkActive directive:

->nested routing:

->routing inside a component

->use children array(its array of routes) inside this component route

->and then use router-outlet directive inside the component and import it
->redirectTo , path: ‘’ :this mean if the path is /About and there is nothing after About it
redirect to vision component and the path will be /About/Vision

->use pathMatch:’full’ to ensure that there is nothing after /About

->to go to another component from html we use routerLink, but from ts we use
service from router module (Router service) ,inject it in the constructor

-use navigateByUrl , or navigate method from router service


->to go to element by its id make the path like this

-send the id as parameter to the function

-or use property binding if we use routerLink

->To get the id or a parameter from url we use ActivatedRoute service from router
module

->use ngOnInit life cycle hook to get the parameter inside it to be sure that the
component was loaded ,so we don’t use the constructor .

-implement OnInit interface

-then use snapshot object and paramMap key to use get method that return the
parameter (return as string so cast it to number)
-use (?) if the value may be null
=============>Lec5

->to go to the previous page or component use button and make click event on it

-then use Location service from common module

-use back() method

->then to make next and previous buttons to go to next and previous product

-use map method on products array to get array of its ids

-then use it in the next() method, and use findIndex() method

-then use navigateByUrl() to go to the next component

-and same for previous()


->but the component will not reload as ngOnInit() doesn’t called after we changed the url to
go to next or previous product , and we have to refresh the page to detect changes

->so don’t use snapshot , but use paramMap property (this of type observable ) that use
observer design pattern and this make the component detect any change on the url , and
use subscripe() method that take a call back function
->Observer design pattern:

->use this pattern when there is changes in a class and want other classes detect the
changes of this class , so these classes should subscribe the class that has changes

-> the class has updates or changes called observable , other classes that should detect
changes called observer or subscriber

->Angular has reactivex library that has this design pattern

->observable vs promise:

- What is the Difference Between Promises and Observables in Angular ? -


GeeksforGeeks

- observable and promise used to handle Asynchronous Operations

-promise use .then() and .catch() or async and await , but observable use subscribe

-async logic code in promise implemented any way, but in observable implemented
when we subscribe it

- observable has operators(methods), but promise doesn’t have

-in observable we can unsubscribe , but in promise cant cancel await

->Reactivex library

-use rxjs for javascript (ReactiveX - Observable)

->create observable:

-ng g service Notification

-make array for notification


-then create getNotification method to create obj from observable class on it , import
observable from rxjs

- the constructor of the object take call back function which called when any component
subscribed this object(observable)

-call back function take the observer(subscriber)

-there is 3 methods:

- next() :to make the observer detect the change or updates happed in the
observable

- error() : if there is error

- complete() : if there is no updates in the observable

->want to send every 2sec element from notification array to the observer:

-use setInterval() , observer.next() ,if array finished call observer.complete(), if


the element is empty call observer.error()

-but function should return the observable , it is generic and its type is the type
of array notification
->then make home component(subscriber) when loaded subscribe the observable in the
notification service:

-inject the service in the component , implement OnInit to use ngOnInit() as we


need to subscribe when the component is loaded

-call subscribe method and handle on it the next , error and complete

->there is error : if the observable completed or there is an error the interval not
stopped(still called every 2second)

-so on the call back function of the observable we should return object which is
unsubscribe method and clear interval on it
->unsubscribe function called when it completed or there is error and if the
component want to unsubscribe (one of the difference between observable and
promise is the observable can unsubscribe)

-home component subscribe the notification observable, but we want to


unsubscribe when navigate to another component

-so we have to unsubscribe in the destroy life cycle , implement OnDestroy to


unsubscribe in ngOnDestroy() method

-create member variable of type subscription (import it from rxjs)

->operators of observable: ReactiveX - Operators

-there is operators which create the observable like from and interval

-map and filter operator: use pipe()


->types of observables:

-subject observable: ReactiveX - Subject

-it acts as observable and observer(others can subscribe on it and it can subscribe on
other observables)

-there is two types of observable:

-hot observable: the code on it executed even if it have no subscribers

-cold observable: the code executed if there is subscriber

-BehaviorSubject: if there is a subscriber it will send the items for it, and if there is a
new subscriber it will send for it the last item sent to the previous subscriber then send
other items.

-PublishSubject: if there is new subscriber will send other items without last item in
previous subscriber

-ReplaySubject : send all items


->create BehaviorSubject:

-create login component , user Authentication service

-we should save the token in the local storage when user login in using setItem(), and
remove the token when logout using removeItem() , getItem() to know if the user logged or not

->create 2 buttons:

->on login ts inject userAuth service


->in the header create to links for login and logout(when logged in show logout link and when
logged out show login )

->but now header will not change the links else if we refresh the page because
ngOnInit() doesn’t called again

-so we want to listen on changes by subscribe on the observable

-use BehaviorSubject which act as observable and observer:

-on the service create private member of type BehaviorSubject(generic type) ,


and getter function for this member

-then on the component subscribe on the observable


============>Lec6

1-Guards:

->ng g guard auth

-> In Angular applications, it is often necessary to protect certain routes to prevent


unauthorized access. The Angular Router provides a feature called Route Guards, which allows
you to control access to routes based on specific conditions.

->there is 4 types of guard:

-CanActivate: this guard executed when I go to the component

- CanDeactivate: when I leave the component(like when we leave a page of


form)

- CanActivateChild: guard on children to know if the parent can see children

-CanMatch

->use CanActivate to handle login:

-guard is a function of type CanActivateFn which imported from router module, this
function return boolean

-then put the guard on the rout that I want,on product route we use another property
called canActivate that take array of guards
->authGuard function return true if the user authantecated(logged in ), and false if unAuth

->so we want to inject userAuth service, but authGuard is a function not class:

- use inject() method imported from core module

-then use getUserLogged method from the service

-if the user isn’t logged , inject router service and use navigateByUr to go to login
component
2-use API ( json-server - npm)

->create folder (server), then from cmd (npm init) , npm i json-server

->then create file db.json and create array of products and categories

->then to run it from cmd (json-server db.json --watch)

-> create ApiProducts service

-> to use json file or API on the products service , should use http module

-go to app.config.ts file , then in the providers array call provideHttpClient()


(which has HttpClient) to make the http seen in all the project

(HTTP Client • Overview • Angular)

-inside provideHttpClient call withFetch method


->in products service inject httpClient service , so we can use get ,post , delete , put
methods and others

-> create getAllProducts method, that use get() method which take url that receive the
request

->get() return observable <Iproduct[]>, so getAllProducts return observable<Iproduct[]>


, and the component which need this function has to subscribe to get the response

->getProductById method return observable of Iproduct , and take the id , so the path will be
products/${id}

-> getProductByCatId method return observable<Iproduct[]>, it take catId so the path should be
products?catId=${catId}

->http://localhost:3000 is a base url, and it may change so we make it as a variable

-in src folder create new folder for environments(ng g environments)

-this folder has 2 files: environment.development.ts, environment.ts and they have a


variable called environment ,on this we make variable called baseUrl in the 2 files
->then on products component inject ApiProducts service , and implement OnInit to use
ngOnInit() to subscribe on getAllProducts method on it not on the constructor

->then ngOnChanges on it subscribe on getProductByCatId


->3-Forms: Forms • Overview • Angular

->create add-product component, make a button for it in the header and a path in the
routes, and create array of categories in ts file
->then use two-way binding to get the data from the form(html) and use it in ts file

->in ts file create member call newProduct to get the data from html on it

->use ngModel , and use name attribute for each input


->to log an object as json not string use pipe(json)

->then handle submit on the form

->in add-product ts file : inject apiProduct service to use addProduct method , and
subscribe on the method as it return observable

-in error: log the error

-in next : show alert for done (SweetAlert2 - a beautiful, responsive, customizable and
accessible (WAI-ARIA) replacement for JavaScript's popup boxes), then go to products
page so inject router service to use navigateByUrl

->then to make validation on the form :use template-driven form if the form is simple and make
the validation in html file , but reactive forms for dynamic forms if the user can change input in
runtime and handle validation in ts file
->use template-driven forms approach : Template-driven forms • Angular

->make submit button disabled if any input not valid, so put a reference on the
form with value ngForm, then on submit button use key invalid at the form
reference

->for Name input: required, apply regular expression using pattern attribute,

-and should show error message, using classes like ng-touched,ng-valid

-then put reference with value ngModel on the name input,so if the input
invalid and touched show message error

-if theres many errors use key object called errors for each error and use (?) as
it may be null
==============>Lec7:

1-send headers with request:

->in user-auth service create method to return the token

->in api-product service: we have getAllProducts which is get request, and used from
httpClient the get method which take url as first parameter,and it take options which is
an object and we can send headers on this object using key(headers) and its value is an
object from HttpHeaders

->in addProduct method which is post method as it use post method from httpClient,
post method take url and body, and also take options like get

->in getProductByCatId we send a query string(/products?catId=${catId}) to know that it


is the id of category

-but we can use opthions object and use from it (key params) which is an object of
HttpParams, and send query string on it using set method
-if there is more than one query string , make variable of type HttpParms and append on
it query strings

2-interceptor:

->It is a layer between my application and the server, any request from app before
arrives to server it passes by the interceptor, and also the response

->in the interceptor we handle any logic we want to apply for all requests or responses
like send the authorization header with any request , and if we want to check on the
status of any response

->create interceptors folder in app folder , and create auth.interceptors.service.ts file on


it

->before angular 17 interceptor was a class , but in angular 17 it is a function which


called with any request or response, its first parameter is object from HttpRequest
which is generic so its type will be <any> for any type of requests, and second parameter
is next method of type HttpHandlerFn

->then go to app.config file ,in providers array which has providersHttpClient method ,
this method has withFetch() to use fetch api not ajax, and will take another function
called withInterceptors() which take array of all interceptors so we have to import the
function of interceptor,and this to make any request or response use this interceptor
->if we want to check if the request is POST we have to append another heade:

-so use req.method ,and we have to clone the request object as we cant change
the request so use clone() method

->to use any response we have to subscribe on next() method as it return observable by
using pipe() method , and use tap() operator on it to get the data in observable which is
the response

-import rxjs to use tap operator

-tap take a call back function which called whith the next() or error() method of
the observable

-the return of observable is HttpEven so it may be any thing not response so we


have to check on the return
3-Lazy loading:

->for single page application if the app has a lot of components if all of them loaded at
the beginning this Slows down the performance, but by using lazy loading we can make
some component not loaded at the begging

->to make the component lazy loaded:

-instead using key component name like this (component:productsComponent)

-use loadComponent key , its value is a function which calls import() method, and the
import take the ts file pass of product component

-import() returns promise, so use then() to get the response on it as obj which has
component name, so the product component will be loaded when the user use it

->note: we can make image or any thing lazy loaded not only all the component

->Eager loading: it is the reverse of lazy loading


4-Reactive forms: second approach to handle form(first one is the template driven forms)
Reactive forms • Angular

->import reactive forms module, and handle the form in ts file not html because it used
for complex forms like when we get array of inputs from user or if the input should be
changed at runtime

->in the template driven forms the validation is html validation, but in reactive forms is
custom validation

->ng g c Register, then route it and make link in the header

->use any bootstrap form(take name , email and password from user)

->in template-driven forms we use two way binding to get the value of each input

->but in reactive forms to use the value of inputs in ts file :

-we want to create the form in ts file, so create member variable of type
FormGroup imported from forms module, and its value is an object of
FormGroup

-this object has name,eamail and password of type FormControl

->to connect the form created on ts file by the form in html file , on html form use a
directive [formGroup]=”form name in Ts file”

-and each input should have name attribute , and another attribute called
formControllName to connect this input by the name of the input in ts
->add another input to the form for address which is object of two values{city , street}

-in ts add another key called addres which is object of formGroup not
formControll,because it contains two other objects (city and street of type form
control)

-in html create input for city an street and connect them by ts by adding
formControlName attribute for them

-but we should put these two inputs in parent div or container , and this
container has formGroupName attribute
->to make validation for reactive forms:

-handle submit on the form

-make the button disapled if the form invalid

-in ts file each FormControl() take first parameter the intial value for input, then
take array of validatorOrOptions

-in this array use validators object to applay validation like validators.required,
and use pattern() method for regular expretion

-then on the input in html write error messages , check the error using
userRegForm.get(‘controlFlowName’)?.errors.[validation]

->instead using userRegForm.get(‘controlFlowName’) every time we need check on


error : in ts make a read only proberty using get keyword that return
userRegForm.get(‘controlFlowName’) , and use it in html(name?.errors),and use
name?.touched&&name?.invalid
->when submit we should make post request and send the object of the data and check
on the status of the response (on register() method in ts )

->if we make a form for update any data like update product or user information ,the
old data should be in the inputs of the form and then modify it

-so we have to use ngOnInit() to make a get request when the component
loaded to get the user or product with id equal the id in url

-and the response will have the new data ,so use setValue() method to set the
new data (name:response.get(‘name’)), but by using this method we have to set
all values

->if we don’t want to set the passward use patchValue() method

->so we want to add another input in the form for phoneNumbers as array of numbers:

-in ts make a new key phoneNumbers which is object of type formArray which
take array of formControl
->in html:create input for phones a button + to add another phone number

-put the input in container or div with attribute formArrayName , and the input
take attribute formControlName

-on button+ handle click event to addNewPhone

-make read only property for phones array ,the return as FormArray

-then use this phones property in the addNewPhone method to push on the
array of phones

-then in html to repeat the input we have to loop on the phones in the div of the
input, and make binding on formControl attribute to have the value of the index
in the array

->in ts instead using formControl and formGroup , we can inject formBuilder service

-change every formGroup and use fb.groub(), formArray by fb.array() ,and don’t
use formControl but make the values as array
===========>Lec8

1-NGRX(Reactive state for Angular) NgRx

->it is a library used to share data between components

->If the components are related(parent and child) we used @Input() and @Outout()
decorators, but if it isn’t related we used services

->we use NgRx library if the data we want to share is large

->it is a state management life cycle: -state is the changed data that I want it to be
shared

1-store: put the shared data in this store

2-selector:one of NgRx conpomnents, if any component want to get or select


the data from store it use this selector

3-actions: if the component want to change the value in the store then dispatch
or fire an action

4-reducer:after the component fired the action, this action is passing by the
reducer which has the logic that we want to do to change the value

5-effects: it is a side effects after change the data in the store the the side
effects do some thing with this changed data like go to the api or save data in
local storage
->we want to make counter and make it shared between all components in the app

->install library: ng add @ngrx/store@latest

->after installation it added provideStore() method to providers array in app.config.tsfile


,so it is first thing(1-store)

->in app folder create folder store for NgRx

->in store folder create folder for counter, then make two ts files for actions and
reducers

->in actions file: call createAction() method that return the action to change the
counter, and its parameter is a string for the name of the action ,so any
component want to change the counter will dispatch this action ,(second thing
2-actions)

->in reducer file: write the logic to change the counter, call createReducer()
method, its first parameter is the initial state or value for the data (counter)

-then it take on() method to listean on the action, this method take the
name of the action , then take a call back function that take the
state(last changed value of the counter) and do the change on it like
increase or decrease this state,(then 3-reducer)
->then in app.config.ts , in provideStore() it take object of all thing I want to be
shared , so it take counterReducer, at begaining the key(counter)take the initial
value (initialState) from reducer file

->then make home component use the counter (4-selector)

-first inject store service to use methods to read values from store or despatch
any action, store service is generic and take object for type or values in the
store(Store<{counter:number}>)

-create member variable to get the data from store on it, its type is observale
and it is generic of type number because the type of counter in reducer is
number

-then call select() method that take the name of the kay we write it in
provideStore({counter:counterReducer}) which is counter, then it return an
observable to subscribe on this variable(counter) if any other component
change it, and save this value in another member( count) to use it in html

-instead using another member(count) and subscribe , we can use the observale
member(counter) in html , but we have to use a pipe (async)
->then make a button in home component to change the counter:

-handle event click on the button

-then in ts file , we injected store service, so we want to use from it the dispatch()
method that take the action name

->each value in the store can have more than action, like counter we can make another action
on it like decreaseCounter,and add another on() method for it in the reducer
->make another value in the store for the language if it english make the direction of the page
from left to right, and if any ine change it to arabic so change the direction to be from right:

->in store folder create folder Language,and make two files for action and reducer

->in action: call createAction() ,it take the type(any name for the action),

-then it should take props method:this method generic that it takes an object for the
type of new value

->in reducer:create variable for initial state,then call createReducer that take the initial
state and on() method to listean on the action , that take action name and call back
function for the logic(to change language)

-call back funck take the state for the value and action to get the value from props
method on it

->in app.config.ts add key for languageReducer

-> in app component in ts file: inject store service<> with type of language:string

-create member(observable), use $ with names of observable members

-use select method


->in html we want change direction , so bind on dir attribute

->then in ts make member variable for direction with initial value(ltr:left to right), then
subscribe on the observable member to change the value of dir

->in header component add button to change lang

-then in ts:create member variable (observable) to select the value using select
method,and another member to get the new value on it by subscribe on the observable
- from store service use dispatch(),that take action name and inside it send new value
for language that will be used in props method in creatAction

->note:ngrx is a state managent so if we change the values in the store and then make
refresh for the page the values will have the initial values not the last value,if we want
to save the change use DB

->or we can save the last value at local storage using Effects:

- ng add @ngrx/store@effects, affter install effectas package there is a new


method for provideEffects in providers array

-in language folder create new ts file for effects lng.effects.ts

-in this file create a class for effect(it is a class not method like actions and
reducer), and use @injectable() decorator on the class

-inject Actions service from effects module

-create member variable saveLanguage its value is the return of createEffect()


method

-this method take call back function and use on it the action service to call pipe
method (()=>this.actions.pipe())that will have any action dispatched and select
from them the action of language to make on it side effect to store it in local
storage

-to select the action use ofType(languageAction) operator that take action name
-second operator for pipe is tap method that take call back function which take
the action dispatched type((action)=>) and on this call back function we save the
value in local storage

-the last operator for creatEffect() is an object that has dispatch:false to stop
getting another dispatched actions

->add the effect to provideEffects()

->then in reducer file make the initial value equal the value in local storage

You might also like