Angular 2 :how to bind four services in a single call - html

i have referred two backend service on a success of the first service, its solved my problem for two backend services.but i have three backend services, on the success of first service, second services should call and on the success of second services, third should service call.
please help me.
service.ts
Firstservice
gethrdata(param)
{
var respone: any;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let authToken = localStorage.getItem('auth_token');
console.log(authToken);
headers.append('X-auth-Token', authToken)
return this._http.post('http://localhost:8080/ada/api/v1/client/'+param+'/hrdata', '', {headers} )
/*.map(res => res.json())*/
.map((res) => {
respone = res;
console.log(respone);
return respone;
});
}
Secondservice
getflagloa(param)
{
var respone: any;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let authToken = localStorage.getItem('auth_token');
console.log(authToken);
headers.append('X-auth-Token', authToken)
return this._http.get('http://localhost:8080/api/v1/client/'+param+'/loa', { headers })
.map(res => res.json())
.map((res) => {
respone = res;
console.log(respone);
return respone;
});
}
Thirdservice
insertloa(param)
{
var respone: any;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let authToken = localStorage.getItem('auth_token');
console.log(authToken);
headers.append('X-auth-Token', authToken);
/* let options = new RequestOptions({headers:headers});*/
return this._http.post('http://localhost:8080/api/v1/client/'+param+'/loadata', '', {headers} )
/*.map(res => res.json())*/
.map((res) => {
respone = res;
console.log(respone);
return respone;
});
}
now how can i call these services on success of prevoius service.

Related

i cant fix the .map on http post client

public postForObjecty(endpoint: any, data: any) {
return new Promise((resolve, reject) => {
let url = this.createBasicUrl(endpoint);
let _data = this.arrangeData(data);
let headers: any = new Headers()
let token = `Bearer ${RestProvider.BEARER_TOKEN}`;
headers.append('Authorization', token);
this.http.post(url, _data, { headers: headers })
.map((res: { json: () => any; }) => res.json())
.subscribe((data: unknown) => {
resolve(data);
}, (err: any) => {
reject(err);
});
});
}
i want to post and get methond to backend but i cant fix this code
.map
this doesnt work,
if i could fix this .map method it will be done
You want to use RxJS map method.
For that you need to .pipe the observable stream like so:
public postForObjecty(endpoint: any, data: any) {
return new Promise((resolve, reject) => {
let url = this.createBasicUrl(endpoint);
let _data = this.arrangeData(data);
let headers: any = new Headers()
let token = `Bearer ${RestProvider.BEARER_TOKEN}`;
headers.append('Authorization', token);
this.http.post(url, _data, { headers: headers })
.pipe(map((res: { json: () => any; }) => res.json()))
.subscribe((data: unknown) => {
resolve(data);
}, (err: any) => {
reject(err);
});
});
}
By default the Angular HttpClient will handle processing the JSON response for you. Assuming you are using this service, this means your map here is not necessary and can be removed entirely.
public postForObjecty(endpoint: any, data: any) {
return new Promise((resolve, reject) => {
let url = this.createBasicUrl(endpoint);
let _data = this.arrangeData(data);
let headers: any = new Headers()
let token = `Bearer ${RestProvider.BEARER_TOKEN}`;
headers.append('Authorization', token);
this.http.post(url, _data, { headers: headers })
.subscribe((data: unknown) => {
resolve(data);
}, (err: any) => {
reject(err);
});
});
}
If you do need the full response, such as the HTTP status code you can pass observe: 'response' into the options object the post function accepts. The Angular documentation goes into good detail on this.
As an FYI, in older versions of Angular that had a now deprecated service called Http and you would need to call .json() all the time.

Running Angular 4 app using a JSON server

I'm trying to run an Angular 4 app while trying to use a JSON server that it has been coded with. The problem I'm having is that I don't understand how an Angular 4 app running on port 4200 can communicate with the JSON server on port 3000 at the same time. The app is an example of CRUD but when I try to add something, nothing gets posted.
This is my article.service.ts:
#Injectable()
export class ArticleService {
//URL for CRUD operations
articleUrl = "http://localhost:3000/articles";
//Create constructor to get Http instance
constructor(private http:Http) {
}
//Fetch all articles
getAllArticles(): Observable<Article[]> {
return this.http.get(this.articleUrl)
.map(this.extractData)
.catch(this.handleError);
}
//Create article
createArticle(article: Article):Observable<number> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: cpHeaders });
return this.http.post(this.articleUrl, article, options)
.map(success => success.status)
.catch(this.handleError);
}
//Fetch article by id
getArticleById(articleId: string): Observable<Article> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: cpHeaders });
console.log(this.articleUrl +"/"+ articleId);
return this.http.get(this.articleUrl +"/"+ articleId)
.map(this.extractData)
.catch(this.handleError);
}
//Update article
updateArticle(article: Article):Observable<number> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: cpHeaders });
return this.http.put(this.articleUrl +"/"+ article.id, article, options)
.map(success => success.status)
.catch(this.handleError);
}
//Delete article
deleteArticleById(articleId: string): Observable<number> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: cpHeaders });
return this.http.delete(this.articleUrl +"/"+ articleId)
.map(success => success.status)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body;
}
private handleError (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.status);
}
}
This is my db.json:
{
"articles": [
{
"id": 1,
"title": "Android AsyncTask Example",
"category": "Android"
}
]
}
I have backend service running on port 5005, and app running on 4200, in order to "talk" with each other I have set up proxy.config.json file which looks like this
{
"/api/*":{
"target":"http://localhost:5005",
"secure": false,
"logLevel": "debug"
}
}
and when I serve my app I run
ng serve -open --sourcemap=false --proxy-config proxy.config.json command.
You can also try to do something like this.

Ionic 2 Json parse

How can i parse json data
data = "{\"msg_ok\": \"Uye olusturuldu\", \"user_id\": 181, \"token\": \"8650bfe987a3d619445f3d4905e1ae863e4be85f\"}"
I want to use token data
I tried like this code but not working..
Thanx to now
var headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json' );
//headers.append('Authorization' , 'Basic '+ btoa(tok));
let options = new RequestOptions({ headers: headers });
let postParams = {
username: this.uyelik['username'],
email:this.uyelik['email'],
password:this.uyelik['password']
}
this.http.post("https://deneme.com/api/v1.0/users/", postParams, options)
.subscribe(data => {
console.log(data['_body']);
this.veri = data['_body'];
this.veri = JSON.parse(this.veri);
console.log(this.veri['token']);
}, error => {
console.log(error);// Error getting the data
});
I SOLVED PROBLEM ;
var headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json' );
//headers.append('Authorization' , 'Basic '+ btoa(tok));
let options = new RequestOptions({ headers: headers });
let postParams = {
username: this.uyelik['username'],
email:this.uyelik['email'],
password:this.uyelik['password']
}
this.http.post("https://iothook.com/api/v1.0/users/", postParams, options)
.subscribe(data => {
//console.log(data['_body']);
veri = data['_body'];
veri= veri.slice(1, -1);
veri = veri.replace(/\\/g, "");
veri = JSON.parse(veri);
console.log(veri.token);
}, error => {
console.log(error);// Error getting the data
});
Try This.
this.http.post("https://deneme.com/api/v1.0/users/", postParams, options)
.map((res: Response) => res.json())
.subscribe(data => {
console.log(data['_body']);
this.veri = data['_body'];
this.veri = JSON.parse(this.veri);
console.log(this.veri['token']);
}, error => {
console.log(error);// Error getting the data
});
Parse like this-
var a = '{\"msg_ok\": \"Uye olusturuldu\", \"user_id\": 181, \"token\": \"8650bfe987a3d619445f3d4905e1ae863e4be85f\"}';
a.replace(/\//g, "");
var token = JSON.parse(a).token;
console.log(token)

Angular 2:Not able to get a token in another component which is stored in local storege

I have one application which include login and home component,
login.service.ts
let body = JSON.stringify(data);
console.log("logged in user",body);
return this._http.post('http://localhost:8080/api/user/authenticate', body, { headers: contentHeaders })
.map(res => res.json())
.map((res) => {
var token1:any = res;
console.log(token1);
if (token1.success) {
localStorage.setItem('auth_token', token1.token);
this.LoggedIn = true;
}
return res.success;
});
}
isLoggedIn() {
return this.LoggedIn;
}
in this service i am getting token in variable token1 and isLogged method contain
constructor(private _http: Http) {
this.LoggedIn = !!localStorage.getItem('auth_token'); }
Login.component.ts
login(event, username, password)
{
this.loginService.login(username, password)
.subscribe(
response => {
this.router.navigate(['/home']);
alert("login successfull");
},
error => {
alert(error.text());
console.log(error.text());
}
);
From this login i can able to authenticate and and its routing to home component,
Home.serice.ts
getClientList()
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let authToken = localStorage.getItem('auth_token');
headers.append('X-auth-Token', 'authToken')
return this._http.get('http://localhost:8080/api/v1/client/list?isClient=Y', {headers})
.map(res => res.json())
}
Home.component.ts
onTestGet()
{
this._httpService.getClientList()
.subscribe(
data => this.getData = JSON.stringify(data),
error => alert(error),
() => console.log("finished")
);
}
now question is how can i access that token in home component which is in token1 varible(login) i have tired to getitem token.but i am getting token null.please anybody help me.
thanks in advance
localStorage.getItem('auth_token')
This should work, but you are getting null, because lifecycle of the data different.
I suggest you to use Subject construction for this purpose, especially you already have service with data.
Example:
loginInfo$ = new Subject();
private _logininfo = null;
getLoginData () {
if(!_logininfo) {
this.http..... { this._loginInfo = data;
this.loginInfo$.next(data); }
return this.loginInfo$.first()
}
else return Observable.of(this._logininfo);
}
So now, your service at the same time storage of data and handler for missing login.

Angular 2 HTTP GET method not returning any header with URL

I am not getting the URL headers with a token in HTTP GET method and also GET method showing OPTION angular 2 typescripts.
Please help me.Thanks
Component.ts
onTestGet(Y)
{
var jwt = localStorage.getItem('id_token');
var k:string = localStorage.getItem(jwt);
var authHeader = new Headers();
authHeader.append('Content-Type', 'application/json');
if(k) {
authHeader.append('Authorization', 'Bearer ' + k);
}
return this._http.get('http://localhost:9095/api/v1/client/list?isClient=Y', {headers:authHeader})
.map(res => res.json())
.subscribe(
data => this.getData = JSON.stringify(data),
error => alert(error),
() => console.log("finished")
);
}