Observable
Observable
An observable can be thought of as a data source [(User Input)Events, Http Requests, Triggered in Code].
Now in our Project an observable basically just an object we import from third party package (rxjs)
The observable here is implemented in such a way that it follows the observable pattern(so we have an
observable and we have an observer in between we have a stream, a time line and on this time line we
could have multiple events emitted by the observable or data packages which is depending on the data
source of that observable . so the observable could emit data because you trigger it to do so,you could
be do that programmatically. It could be connected to a button and therefore when ever the button is
clicked an event in a data package is emitted automatically or the angular http service does it if it
connected to a http request. So when the response returns, the response is emitted as a data package.
And there are dozens of other data package too.)
So the other part is a Observer. This actually is your code you could say it's the subscribe function
you saw earlier or at least it has something to do with that. There you have three ways of handling data
packages.
i.e. you can handle the normal data ,you can handle errors or you can handle the completion of
observable, becoz these are the three types of data package you can recieve and in this hook / boxes
you could say we write our code which gets executed. So we can determine what should happen if I
receive a new data package what should happen if i receive a error what should happen when the
observable eventually completes side note an observable does not have to complete for ex there are
observable hooked up to a normal button which never complete because how would you know when it
complete becoz the user click the button how often the user wants right. Our observable is like the http
request on the other hand will have a clear end and will complete eventually becoz once the response is
there what else should happen its done.
So this is how observable generally works. and off course it is used to handle asynchronous tasks
becoz all these data sources here like user events triggered in your code or a http request are
asynchronous , we don’t know when they will happen and we dont know how long the will take , so if
you execute your normal application code you don’t to wait for these events or you dont wnt to wait for
the completion of http request becoz that would block the program /would block your logic.Therefore
we need methods to solve such asynchronous task and historically you might have used callbacks or
promises.
Project
In our project I am using an observable , the params object observable angular ships with in the
@angular/router package to handle the change of these router parameters becoz just as a refresher
angular doesn't re render the whole user component just becoz the parameter changes therefore it uses
the observable to still give us a chance to react to this updated id.
In the las section we implemented gow to subscribe to anything changes in the component after
that component has been loaded i think it works kind of intuitive becoz we can basically accept that
route parameters as some kind of asyn object and we subscribe to any events that might send to us in
this case the rout params and we simply handle that by the call back we pass to the subscribe method
keep in mind its just simply the arguments we pass then we simply extract the id in this case.
the subsribe method is just a observer thereforewe could implement more call backs . we only
implemented callback to handle the data call back , but the subsribe method always takes 3 arguments ,
we could also implements an anonymous fun which gets executed in the case of an error and one which
gets executed once the observable completes
we are subsribing to such an observable which wraps the data sourse( the data source being code in
angular we could say) which emits a new pameter when ever we click a link so our click is the triggering
events in the end But again angular sets up the observable and then pushes it to give us a new data
piece
we can create an observable with the help of the helper methods , so there we got couple of helper
methods which will create one for us for example interval. Now interval is a very simple way of creating
a new observable here we simply pass a number and that number will be the miliseconds it should wait
between emiting data automatically so it will do data emiting automatically for us, and for that to work
we actually need to add one import 'rxjs/Rx';
there on the other hand i have an event which gets fired when i click one of the three status buttons
Services
Angular provides a much better way to use this services so we do not need to create the instances
manually . so lets get rid of this manually creation let me tell u which tool angular offers us to get acess
to our services
Dependency injector
angular offers us some great tool which will give access to the service class so that we can use the
methds in the other Components available in our application which has been definds in our service class
dependency simply means something that our components depends on in other word they depends on
the service class to use the methods
injector simply means injects the dependency or injects the instance of our services
so all we need to do is we need to inform angular that we require such an instance we will do this by
creatinng a constructor in our component class where we want to use the services
-->the angular dependency injector actually a hierarchical Injector if we provide the services in to one
compentent all its chiLd component will able to access these services but it won't propagate up
the app modelue is the highest level component ----> then app component ---> then the component
with no child
so i mentioned earlier the highest possible area to provide services is our app-module
there we can aslo have a provider which indicates our service class , and with that lil additions to that
providers we can recieve the same instance of our service class unless we override it in other class
we have seen our query parameters are gone when ever we navitate away from our single serer
component to the edit component so we would have to preserve them becoz we already set the
information at the point of time we visit this single server component now we need to preserve this
information once we navigate one step further to the edit server component to preserve this
information we get a simple way of doing so, in the single server componet where we navigate we can
add a QueryParamHandlisn gproperty
Redirecting and wild card routes
if we enter anything in the url we can redirect to the component thet we used in the wild card route
caathing all routes which is unknown to angular at that point of thime once it reaches this wild card
route so make sure it should be last line in our routes array.
we already see that our routing takes up some significant space in our app module , so typically if we
have two or three routes in our projects we dont add directly in the app module instead we can add a
new file which is for the application as a whole and this file now will hold a second module(we can
define multiple moudles togather and use them togather in our application we will see later in our
course there we will dive much deeper in to this )this is a super easy use case here We can create a
simple ts class and it recieves @NgModule dEORATOR so this is configured with a javascript object
passing through it(this is a super simple module) and this will handle all routing related task so cut all
our routes from app-module file and paste it in our newly created module and make sure to add all our
inputs , and we dont need to add declaration here becoz these are already are declared in our app
mpdule. And just make sure to add this newly created module to the root module.We also have to
remove the RouterModule from our root module and add the import in our newly created module
Now we need tp configured something in the @NgModule() decorator,we basically have to add
imports angin and in the imports we have to use this RouterModule.forRoots()
this is simply not enough now becoz as i mentioned earlier we simply use this app-routing-moude to
out source our routes there fore we need to add this module back to our main moduleand for this
exports simply tells angular - "hay from this module if i were to add this module to the imports of
anothe module what should be accessible to the module which uses this module as the imports.
ROUTE GOUARD:-
So basically functionalities logic code which is executed before a route is loaded oe once you want to
leave a route ,we may be protect some of our routes we could use a feature offered by angular which
allows us to run some code at a point of time defined by us.
export a class and impements the CanActivate interface this interface is provided by the
@angular/router package so we need to import it and it forces you to have a canActivate method in this
class. the can activate mmthod now will receive two arguments though one is ActivatedRouteSnapdhot
and the state of the router so the RouterStateSnapshot.(import them as well)
you might ask where are we getting these arguments from so keep in mind we ll have soon to find that
angular should execute this code before a router is loaded so it ll give us this data and we simply need to
be handle the data so that is can activate with the argument it requires . CanActivate also returns
something it either returns some Observable so make sure to import it from rxjs package.
this Observable then will wrap a boolean so it will in the end resolve to a true or false value
Or it can run synchroniousely because you might have some gauards which execute some code which
runs completely on the client threrefore it runs synchroniousely or you might have some code which
takes a couple of seconds to finish like we use a timeout in there or we reach out a server in case
therefore run asynchroniously Both ways possible in CanActivate
here we want to be able to log in or log out (just a fake example) for this just say we have auth.service.ts
(any name) In a real application this may reach out to a service which amy allow us to log in or log out
and check our current authentication state
this is one of the most convinient way to keep the user from navigate away or to focus on to controll
where the users are allowed to leave the route or not becoz may be they accidentally click the back
after they were logged in or while thery are changing something it is usefull to ask them to keep going
with the changes or they want to leave with out having any changes.
the resolver will always rendered a component in the end but it will do some pre-loading you could
say it will fetch some data that the component will need later on . of course the alternative is to render
the component or the target page instantly and in the onInIt method of this page you could then fetch
the data and display some spinner while you are doing so. So that is an alternative
But if you want to load it before actually displaying the route this is how you could add a resolver(int
the project )
by creating a server which is then implements the Resolve interface import it from @angular/router
package Now this Resolve interface wrap which ever item or data field you will fetch here in the end ,so
in our project will get a server so we need to define the type here(you could outsource this in to an
interface or a model in general)