RXJS observables

 Rxjs

RxJS is a JavaScript library for the reactive programming using Observables, which makes easier to work with asynchronous or callback-based code.

Rxjs offers us a different type of functions to create a new observable.

What are Observables?

  • Observables are the functions which can return a single value or even multiple values in sequence and they can handle both synchronous and asynchronous tasks.
  • Observables can only run when you subscribe to the data.

next() => for new data
error()
complete()

Once error is reached , no further data transfer possible and also same with complete
inbuilt
interval(1000)
fromEvent('use element here','use action here') 
we can directly subscribe to it

Operators =
for using multiple operators use pipe operator
map=> to return modified data
map(data=>{return data['clientX']})

filter=> return specific data
filter(data=>{return data%2==0})

throttleTime=> to emit event after specific time
throttleTime(2000))

debounceTime=> to emit new data only when no changes are done by user

debounceTime(2000)

distinctUntillChanged=> to be used after debounce time, in this it will only emit data if the new vaue is diifrent from old one
distinctUntilChanged()

Rxjs Subjects are used for transfer of data and with next() function to pass values on demand 


  ngOnInit() {
    // interval(1000).pipe(map((data)=>{
    //   return 'Number '+data
    // }),throttleTime(2000))
    // .subscribe((data)=>{
    //   console.log(data);
    // })
    fromEvent(document.getElementById('b1'),'click')
    .pipe(map(data=>{return data['clientX']}),filter(data=>{return data%2==0}))
    .subscribe(data=>{console.log(data,this.name.nativeElement.value)});

    fromEvent(document.getElementsByTagName('input'),'input').pipe(
      map(data=>{
        return data.target['value']
      })
      ,debounceTime(2000),distinctUntilChanged()
    )
    .subscribe(data=>{
      this.dispName=data;
      console.log(data)
    })

  }





// let obs = of(1,2,3,4,5)

// obs.pipe(reduce((a,v)=>{ // will give one final value
//   return a+v;
// },0))
// .subscribe((d)=>{
//   console.log(d);
// })
// obs.pipe(scan((a,v)=>{ // will give intermediate values also
//   return a+v;
// },0))
// .subscribe((d)=>{
//   console.log(d);
// })
//pluck // works like map function but
//in this we can get the values more precisely from the object
// fromEvent(document.getElementById('i1'),'input')
// .pipe(pluck('target','value'),
//   debounceTime(500),distinctUntilChanged())
// .subscribe((d)=>{
//   console.log(d)
// })

//   }
//MergeMap // merging the values from 2 observables
// when internal observable is emitting the value then only it will emit overall value
// let obs1 = fromEvent(document.getElementById('i1'),'input');
// let obs2 = fromEvent(document.getElementById('i2'),'input');

// obs1.pipe(mergeMap(
//   event1=>{
//     return obs2.pipe(map(event2=>{

//       return  `${event1.target['value']} ${event2.target['value']}`
//     }))
//   }
// )).subscribe(d=>{
//   this.dispName =d;
// })
// switch map it will trigger the internal obsrvable when external is triggered
//, removing all past subscription from the internal observable
let obs1 = fromEvent(document.getElementById('b1'),'click');
let obs2 = interval(1000);

obs1.pipe(switchMap(
  event=>{
    return obs2;
  }
)).subscribe(value=>{
  console.log(value)
})








































CORS Error

 Cross origin request sharing

it can be solved on server side

this is caused as a security implimented to avoid resource sharing accross 2 domains

so for this before routes are handled , headers can be set

app.use((req,res,next)=>{

res.setHeader('Access-Control-Allow-Origin','*');

res.setHeader('Access-Control-Allow-Methods','PUT,PATCH,POST');

res.setHeader('Access-Control-Allow-Headers','Content-Type,Authorization');

})

Rest API with Express ( starter)

 1. install express

npm init

npm install --save express

const express = require('express');
const app = express();

for nodemon use it as development dependency

npm install --save-dev nodemon

and in the scripts use start for nodemon app.js


For following MVC way model view and controller

create 2 folders controllers and routers => controllers will have logic after routes are handled

and in routes routing is handled

Under Routes > routes.js

1. use express 

then routes = express. router()

const express = require('express');
const router = express.Router();

this router has to be exported as module

module.exports=router;

for defining routes use 

router.get('/post',feedcontroller.getpost)

under feed controller => feed.js

create a function for the each routes as diffrent modiles

exports.getPosts=(req,res,next)=>{
    res.json(
        {posts:[{title:"first post",content:"first post content"}]}
        );
}

As it is Api so response is set as Json

router.get('/posts',feedController.getPosts);

in app.js

app.use('/feed',feedrouter);
app.listen(8080);

for parsing incomming request body parser is to be used as json

install it as

npm install --save body-parser

app.use(bodyParser.json());

extracting data from body

exports.createPosts=(req,res,next)=>{
    const title = req.body.title;
    const content= req.body.content;
    res.status(201).json({
        message:'Post created',
        post:{
            id: new Date().toISOString(),
            title:title,
            content:content}
    }    );
};

























Python-1

Python Revision Notes - Comprehensive Study Guide Section 1: Python Environment Setup 4. Different Ways of Creating Python Environment [...