Add Header to the API Http request, Angular 2, Ionic 2 - json

I have an ionic 2 app (which uses Angular 2 Http), i have the code which gets the JSON from the API, however i need to send the app-id, app-key and Accept as a header, this is the main code...
import {Component} from '#angular/core';
import {NavController} from 'ionic-angular';
import {Http} from 'angular2/http';
#Component({
templateUrl: 'build/pages/latest-page/latest-page.html'
})
export class LatestPage {
static get parameters() {
return [[NavController]];
}
constructor(_navController, http) {
this._navControler = _navController;
this.http = http;
this.http.get("https://twit.tv/api/v1.0/people/77").subscribe(data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
console.log("Error with Data");
});
}
And this is how i tried to add the header, however its not working...
constructor(_navController, http) {
this._navControler = _navController;
this.http = http;
var headers = new Headers();
headers.append('app-id', '0000');
headers.append('app-key', 'abc000abc');
headers.append('Accept', 'application/json ');
this.http.get("https://twit.tv/api/v1.0/people/77"),{"Headers": headers}.subscribe (data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
console.log("Error with Data");
});
}
Any ideas?
Thanks

Headers must be set inside the RequestOptions, which is the second parameter http.get()
Besides you have a syntax error in your code. Request options is the second parameter of .get(url, {}), and you wrote like this: .get(url),{}
this.http.get("https://twit.tv/api/v1.0/people/77",{"Headers": headers}).subscribe (data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
console.log("Error with Data");
});
Creating explicitly request options.
let opt: RequestOptions
let myHeaders: Headers = new Headers
myHeaders.set('Content-type', 'application/json')
opt = new RequestOptions({
headers: myHeaders
})
_http.get(url, opt).
After some misunderstanding, I'll leave here you're own code with my suggestions:
constructor(_navController, http) {
/*this isn't necessary, _navController and http are already available for "this. "*/
this._navControler = _navController;
this.http = http;
let opt: RequestOptions
let myHeaders: Headers = new Headers
myHeaders.set('app-id', 'c2549df0');
myHeaders.append('app-key', 'a2d31ce2ecb3c46739b7b0ebb1b45a8b');
myHeaders.append('Content-type', 'application/json')
opt = new RequestOptions({
headers: myHeaders
})
this.http.get("https://twit.tv/api/v1.0/people/77",opt).subscribe (data => {
console.log("Got Data");
this.items = JSON.parse(data._body).people;
}, error => {
console.log("Error with Data");
});
}

Related

HTTP call - req.url is undefined

I want to get data from an API link. Api Link and API-key are correct. When I try it with POSTMAN it returns result. When I run the app with http call it gives this error:
"Uncaught (in promise): TypeError: req.url is undefined
HttpXsrfInterceptor.prototype.intercept...
What is the problem can someone please tell me?
Here is my code.
App module.ts
import { HttpClientModule, HttpClient } from '#angular/common/http';
#NgModule({
imports: [
HttpModule ]
})
home.ts
import { HttpHeaders, HttpClient } from '#angular/common/http';
export class A{
apiUrl = "yyy-yyy-yyy";
constructor(private http: HttpClient){
this.getData();
}
getData(){
let headers = { headers: new HttpHeaders({ 'Accept': 'application/json',
'user-key': 'xxx-xxx'})};
return this.http.get(this.apiUrl, headers).subscribe(res=>
console.log('RES: ', res));
}
}
Error screenshot;
enter image description here
Firstly you want to have a service like that:
service.ts
constructor(private http: Http
) { }
public mygetdata(): Observable<Data[]> {
let headers = new Headers();
headers.append('user-key': 'xxx-xxx');
return this.http.get(this.apiUrl), {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
} else {
return res.StatusDescription.map(data=> {
return new Data(data);
});
}
})
}
Component.ts
public data : Data[];
getdata() {
this.service.mygetdata().subscribe(
data => {
this.data = data;
}
);
}

Angular 2 Service Not Returning JSON from HTTP Response

I'm attempting to return JSON data from a web api, the service collects this fine and when you output this to the console it works and returns what I expect, but when I try to return the data to somewhere outside the service I can only get back 'undefined' with no errors.
Service Method
// Dashboard API Services
getModules() {
this._http.request(this._baseUrl + "Modules/Get").subscribe((res: Response) => {
this.modules = res.json();
});
return this.modules;
}
Service Call (in component)
import { Component, OnInit } from '#angular/core';
import { KoapiService } from '../koapi.service';
import { Http } from "#angular/http";
#Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
modules: any;
constructor(private _koapi: KoapiService) { }
ngOnInit() {
this.modules = this._koapi.getModules();
console.log(this.modules);
}
}
Found a great article on much better way to do this here: https://hassantariqblog.wordpress.com/2016/12/03/angular2-http-simple-get-using-promises-in-angular-2-application/
Changed my code to the following, meaning the service can take any URL now from from the service call as opposed to inside the service:
Service Method(s):
// On successful API call
private extractData(res: Response) {
let body = res.json();
return body || {};
}
// On Erronious API Call
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
// Basic Get
getService(url: string): Promise<any> {
return this._http
.get(this._baseUrl + url)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
Service Call:
// Get Enabled Modules
this._koapi
.getService("Modules/Get")
.then((result) => {
this.modules = result;
console.log(this.modules);
})
.catch(error => console.log(error));
}
1.
const headers = new Headers({
'Content-Type': 'application/json',
'Cache-control': 'no-cache',
Expires: '0',
Pragma: 'no-cache'
});
const options = new RequestOptions({ headers: headers });
You have to send this 'options' along with url.

http get angular2 load to finish

I have the following issue :
I have a request "http get" and I can not receive data, since this is received after loading the entire app.
SERVICES
import { Injectable } from '#angular/core';
import { Http, Jsonp, Headers, Response, RequestOptions, Request, RequestMethod } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class ChartsAPI {
token: JSON;
data_json: any;
constructor(private http: Http, private jsonp: Jsonp) {
this.token = JSON.parse(localStorage.getItem('tokenUser'));
}
getBestSeller( filter: JSON ): Observable<any[]> {
const auth = `Bearer ${this.token}`;
console.log(filter);
const headers = new Headers() ;
headers.append('Accept', 'application/json');
headers.append('Authorization', auth);
const options = new RequestOptions({ 'headers': headers });
this.http.get('https://coimco.herokuapp.com/api/products', options)
.map(res => res.json())
.subscribe(
data => this.data_json = data,
err => console.log(err),
() => console.log(this.data_json),
);
return this.data_json;
}
}
Component
getSeller(filter: JSON) {
console.log(this._chartAPI.getBestSeller(filter));
}
this console browser, the API response is the last to be displayed, when should the first
Screen Shot:

post data in angular2

I am facing the issue of json added being added to the url after calling the service to add the data.
below is my file
first.ts
CreateNew(): void {
this.router.navigate(['/detail', 0]);
}
detail.ts
Submit() {
let templateId;
this.route.params.subscribe(
(param: any) => {
templateId = +param['templateid']; });
if (templateId === 0) {
this.jobservice.addJob(this.job).subscribe(error => this.errorMessage = <any>error);
}
this.router.navigate(['/template']);
}
service.ts
addJob(job: Job): Observable <Job> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(job);
return this.http.post('http://sample/api/Product/AddProduct', JSON.stringify(job), options).map(this.extractData).catch(this.handleError);
}
I am not able to find the issue why it is adding the json data to the url.
When you use the RequestOption, you dont use the method post, get, put or delete. But you use "request". Here is a sample request that works:
post<RQ, RS>(url: string, request: RQ, responseType: RS, withToken: boolean): Promise<RS> {
let postReq: Request = this.createAuthorizationHeader<RQ>(url, request, RequestMethod.Post, withToken);
return this.http.request(postReq).toPromise()
.then(res => {
return this.processingData<RS>(res, responseType);
})
.catch(this.handleError);
}
Then here you add your header to the request:
/**
* This function updates the token in the header
*/
createAuthorizationHeader<RQ>(url: string, requestData: RQ, method: RequestMethod, withToken: boolean) {
let headers = new Headers();
let options = new RequestOptions({
method: method,
url: url
});
/**
* Include token when boolean is passed
*/
if (withToken) {
headers.append('token', token);
options.headers = headers;
}
/**
* create bosy for post and put
*/
if (method === RequestMethod.Post || method === RequestMethod.Put) {
// do something
}
let request = new Request(options);
return request;
}
This should work, remember to use "http.request.." when you use request options
import { Http, Request, Response, Headers, RequestMethod, RequestOptions } from '#angular/http';
...
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers = headers,
body: job
});
let request = new Request(options);
console.log(options);
return this.http.request(options).map(this.extractData).catch(this.handleError);
The issue was that while refresh of page it was showing 404 error.
In app.module.ts
Add imports: import { HashLocationStrategy, LocationStrategy } from '#angular/common';
And in NgMoudle provider, add: {provide: LocationStrategy, useClass: HashLocationStrategy}
which fixed the issue.
This should be working out fine. I have this working on my environment using angular 2.1.0.
import { Http, Request, Response, Headers, RequestMethod, RequestOptions } from '#angular/http';
...
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
method: RequestMethod.Post,
url: 'localhost:51293/template',
headers = headers,
body: job
});
let request = new Request(options);
console.log(options);
return this.http.request(options).map(this.extractData).catch(this.handleError);

angular2: Supplied parameters do not match any signature of call target, even though i have all the needed params

push.component.ts
import { Component, OnInit } from '#angular/core';
import {PushResult} from './dto/pushResult';
import {PushRequest} from './dto/pushRequest';
import {PushService} from './push.service';
#Component({
// selector: 'push-comp',
template:
// `<form (submit)="submitForm()">
// <input [(ngModel)]="element.name"/>
//
// <button type="submit">Submit the form</button>
// </form>
// <br>
`<button (click)="getHeroes()"> get </button> <button (click)="saveHeroes()"> push </button>`,
// templateUrl: 'app/html/heroes.component.html',
providers: [PushService]
})
export class PushComponent implements OnInit {
pushResult:PushResult;
// selectedHero:Hero;
// addingHero = false;
error:any;
element:any;
constructor(private pushService:PushService) {
console.info("in PushComponent constructor()");
}
getHeroes() {
this.pushService
.doSomeGet();
// .then(pushResult => this.pushResult = pushResult)
// .catch(error => this.error = error);
}
saveHeroes() {
var pushRequest: PushRequest = new PushRequest();
// this.pushService.doSelectMessagesAttributesUrl2(pushRequest);
this.pushService.doFeatureCreateNewMessageUrl(pushRequest);
this.pushService.doFeatureSelectPushMessages(this.element);
// .then(pushResult => this.pushResult = pushResult)
// .catch(error => this.error = error);
}
ngOnInit() {
console.info("in PushComponent ngOnInit()");
// this.getHeroes();
// this.saveHeroes();
}
}
push.service.ts
import { Injectable } from '#angular/core';
import {Http, Response, Headers} from '#angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';
import { PushResult } from './dto/pushResult';
import {PushRequest} from './dto/pushRequest';
import {StringUtilsService} from "../shared/stringUtils.service";
#Injectable()
export class PushService {
//private pushUrl = 'http://www.ynet.com'; // URL to web api
// private getUrl = '/app/eladb.json'; // URL to web api
private getUrl = '/SupporTool/ShowConfig?id=4'; // URL to web api
private selectMessagesAttributesUrl = '/SupporTool/Push/SelectMessagesAttributes'; // URL to web api
private postMultiMap = '/SupporTool/Push/FeatureCreateNewMessage'; // URL to web api
private postBoolean = '/SupporTool/Push/FeatureSelectPushMessages'; // URL to web api
private stringUtilsService : StringUtilsService;
constructor(private http: Http) {
this.stringUtilsService = new StringUtilsService();
}
doSomeGet() {
console.info("sending get request");
let headers = new Headers({
'Content-Type': 'application/xml'});
this.http.get(this.getUrl, {headers: headers})
.map(res => res.text())
.subscribe(
data => { console.info("next: "+data) },
err => console.error(err)
);
}
doSelectMessagesAttributesUrl2(pushRequest : PushRequest) {
console.info("sending post request");
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'});
return this.http
.post(this.selectMessagesAttributesUrl, "", {headers: headers})
.map(res => res.json())
.subscribe(
data => { console.info("next: "); console.info(data) },
err => console.error(err)
);
}
doFeatureCreateNewMessageUrl(pushRequest : PushRequest) {
console.info("sending post request");
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'});
var isLimit = true;
return this.http
.post(this.postBoolean, "#limit="+isLimit, {headers: headers})
.map(res => res.json())
.subscribe(
data => { console.info("next: "); console.info(data) },
err => console.error(err)
);
}
doFeatureSelectPushMessages(element : any) {
console.info("sending post request");
let dict = {"limit":"true", "name":"foo"}
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'});
var params = {};
params['push_input_internal_id'] = "1";
params['b'] = "2";
var formParamString = this.stringUtilsService.mapToFormParamsString(params);
return this.http
.post(this.postMultiMap, formParamString , {headers: headers})
.map(res => res.json())
.subscribe(
data => { console.info("next: "); console.info(data) },
err => console.error(err)
);
}
private handleError(error: any) {
console.error('An error occurred', error);
// return Promise.reject(error.message || error);
}
}
push.component.spec.ts
import { By } from '#angular/platform-browser';
import { DebugElement } from '#angular/core';
import { addProviders, async, inject } from '#angular/core/testing';
import { PushComponent } from './push.component';
describe('Component: Push', () => {
it('should create an instance', () => {
let component = new PushComponent();
expect(component).toBeTruthy();
});
});
app.routing.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { PushComponent } from './push/push.component';
const appRoutes: Routes = [
{ path: '', redirectTo: '/push', pathMatch: 'full' },
{ path: 'push', component: PushComponent}
];
export const appRoutingProviders: any[] = [];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
I read this post, but it used to work for me. So i cannt understand what i am missing.
and i get this error after npm start
Build error
The Broccoli Plugin: [BroccoliTypeScriptCompiler] failed with:
Error: Typescript found the following errors:
/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/tmp/broccoli_type_script_compiler-input_base_path-2GTEvnc7.tmp/0/src/app/push/push.component.spec.ts (10, 21): Supplied parameters do not match any signature of call target.
at BroccoliTypeScriptCompiler._doIncrementalBuild (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/lib/broccoli/broccoli-typescript.js:120:19)
at BroccoliTypeScriptCompiler.build (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/lib/broccoli/broccoli-typescript.js:43:10)
at /Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/node_modules/broccoli-caching-writer/index.js:152:21
at lib$rsvp$$internal$$tryCatch (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/node_modules/rsvp/dist/rsvp.js:1036:16)
at lib$rsvp$$internal$$invokeCallback (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/node_modules/rsvp/dist/rsvp.js:1048:17)
at lib$rsvp$$internal$$publish (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/node_modules/rsvp/dist/rsvp.js:1019:11)
at lib$rsvp$asap$$flush (/Users/eladb/WorkspaceQa/SupporTool/src/main/webapp/html/ng2/node_modules/angular-cli/node_modules/rsvp/dist/rsvp.js:1198:9)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
PushComponent expects a PushService instance as parameter
constructor(private pushService:PushService) {
but you don't provide one
new PushComponent(/* parameter value missing */);
If you create an instance yourself with new Xxx() then Angulars DI is not involved and no dependencies are passed.
Only when Angulars DI itself creates PushComponent does it resolve and pass dependencies.
import {beforeEachProviders, it, describe, inject} from '#angular/core/testing';
describe('my code', () => {
beforeEachProviders(() => [PushService, PushComponent]);
it('does stuff', inject([PushComponent], (pushComponent) => {
// actual test
});
});
Don't expect to get a component injected. What you get this way is an instance of the components class (without any change detection running, nor lifecycle hooks being called, ...)
If you want a component, then you need to use TestBed. See also https://github.com/angular/angular/blob/master/CHANGELOG.md