http get angular2 load to finish - json

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:

Related

TypeError: errorResponse.json is not a function - Tried to remove holding response as Json but still facing issue [duplicate]

I am having an issue with my API Service. This service connects to my nodejs backend api.
The error says
ERROR TypeError: res.json is not a function
I am getting this error after recently updated this service to use the HTTPClient instead of Http. Im getting this reponse because im missing the old http with the new? if thats the case is there an new Response and how do i use it?
import { Injectable } from '#angular/core';
import { environment } from '../../environments/environment';
import { HttpHeaders, HttpClient, HttpParams } from '#angular/common/http';
import { Response } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';
#Injectable()
export class ApiService {
constructor(
private http: HttpClient,
private jwtService: JwtService
) {}
private setHeaders(): HttpHeaders {
const headersConfig = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
if (this.jwtService.getToken()) {
headersConfig['Authorization'] = this.jwtService.getToken();
}
return new HttpHeaders(headersConfig);
}
private formatErrors(error: any) {
return Observable.throw(error.json());
}
get(path: string, httpParams: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), params: httpParams })
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
put(path: string, body: Object = {}): Observable<any> {
return this.http.put(
`${environment.api_url}${path}`,
JSON.stringify(body),
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
post(path: string, body: Object = {}): Observable<any> {
return this.http.post(
`${environment.api_url}${path}`,
body,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
delete(path): Observable<any> {
return this.http.delete(
`${environment.api_url}${path}`,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
}
HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.
See Difference between HTTP and HTTPClient in angular 4?
You can remove the entire line below:
.map((res: Response) => res.json());
No need to use the map method at all.
Don't need to use this method:
.map((res: Response) => res.json() );
Just use this simple method instead of the previous method. hopefully you'll get your result:
.map(res => res );
Had a similar problem where we wanted to update from deprecated Http module to HttpClient in Angular 7.
But the application is large and need to change res.json() in a lot of places.
So I did this to have the new module with back support.
return this.http.get(this.BASE_URL + url)
.toPromise()
.then(data=>{
let res = {'results': JSON.stringify(data),
'json': ()=>{return data;}
};
return res;
})
.catch(error => {
return Promise.reject(error);
});
Adding a dummy "json" named function from the central place so that all other services can still execute successfully before updating them to accommodate a new way of response handling i.e. without "json" function.

Getting 502 (Bad Gateway) when uploading image to Cloudinary via API call

I'm trying to upload image to Cloudinary via their rest api but i keep getting a 502 (Bad Gateway) response. Please help!
I have tried searching for solutions online but could not find any that addresses the issue
The service that connects to Cloudinary API is as below:
import { Injectable } from '#angular/core';
import { HttpClient,HttpHeaders} from '#angular/common/http';
import {Observable} from 'rxjs';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type' : 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
})
};
#Injectable({
providedIn: 'root'
})
export class ImageService {
CLOUDINARY_URL = 'https://api.cloudinary.com/v1_1/xxxx/image/upload';
CLOUDINARY_UPLOAD_PRESET = 'xxxx';
constructor(private http: HttpClient) { }
uploadImage(file: any):Observable<any> {
console.log(file);
let formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', this.CLOUDINARY_UPLOAD_PRESET);
console.log("upload image in progress");
return this.http.post<any>(this.CLOUDINARY_URL, formData, httpOptions);
}
}
The function that reads user selected image file is as below:
cloudFileChangeListener(event: any): void {
let file = event.target.files[0];
console.log(file);
this.isImageUploading = true;
this.imageService.uploadImage(file).subscribe(response => {
this.isImageUploading = false;
console.log(response);
this.imageUrl = response.secure_url;
}, err => {
this.isImageUploading = false;
console.log(JSON.stringify(err));
})
}
Error returned is as below:
{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":502,"statusText":"Bad Gateway","url":"https://api.cloudinary.com/v1_1/xxxxx/image/upload","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://api.cloudinary.com/v1_1/dexihbyv4/image/upload: 502 Bad Gateway","error":"<h2>Incomplete response received from application</h2>"}
N:B. The file is being uploaded locally.

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;
}
);
}

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

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

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");
});
}