ionic 3 native HTTP does not let me access JSON data - javascript

I am using ionic 3 native HTTP to do a POST request to my backend server which returns JSON data but when I try to access the object from the variable I get an error:
[ts] Property 'InRepair' does not exist on type '{}'.
any
Not sure what I am doing wrong.
I made my POST request function a provider and here is the code for that
HttpProvider.ts
import { HTTP } from '#ionic-native/http';
#Injectable()
export class TekItapiProvider {
apiURL = 'myAPISeverURL';
constructor(private http: HTTP) {
}
doPost(url, data) {
var endpointURL = this.apiURL + url;
return new Promise((resolve, reject) => {
this.http.post(endpointURL, data, this.headers)
.then(data => {
resolve(data.data);
})
.catch(error => {
console.log(error.status);
reject(error);
})
})
}
}
This is where it is being called and where I try to access the object. In status I can access .completed because it gives me the error: [ts] Property 'InRepair' does not exist on type '{}'.
any
request.ts
this.httpProvider.doPost(myURL, '')
.then((status) => {
if (status.completed == 'Yes') {
}
},(err) => {
})
Do you guys know what I am doing wrong here?

Related

How to catch custom java8 exception from react?

Following code generates exception as UserAlreadyExist.
Optional<User> userCheck = userRepository.findByUsername(createRequest.getUsername());
if(StringUtils.hasText(userCheck.get().getUsername())){
String errorMessage = "User already exist: "+ userCheck.get().getUsername();
throw new UserAlreadyExistException(errorMessage);
}
When i try to get error message from my react app with these codes i only get Internal server error message. My header contains header token and application/JSON header.
export const createUserService = (data) => {
return new Promise(((resolve, reject) => {
axios.post(USERS_BASE, data, getHeaderWithToken())
.then(function (response) {
resolve(response);
})
.catch(error=>{
console.log(error)//returns "Internal Server Error" message
console.log(error.response) // returns object with empty message field and other parameters.
reject(error)
})
}));
};
How can i get the error message i sent like
String errorMessage = "User already exist: "+ userCheck.get().getUsername();
throw new UserAlreadyExistException(errorMessage);
this is my UserAlreadyExistException class btw.
public class UserAlreadyExistException extends RuntimeException {
public UserAlreadyExistException(String message) {
super(message);
}}
You can return custom Response with #RestControllerAdvice for the custom exception you are throwing.
Please check the example below.
#RestControllerAdvice
public class ControllerExceptionHandler {
#ExceptionHandler(value = {UserAlreadyExistException.class})
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ErrorMessage userAlreadyExistException(UserAlreadyExistException ex, WebRequest request) {
ErrorMessage message = new ErrorMessage(
status,
date,
ex.getMessage(),
description);
return message;
}
}
It will be much easier for you to see the error in your Frontent application with a Response that you will return like this.

Property 'authorization' does not exist on type 'Request'

Consider this code:
setContext(async (req, { headers }) => {
const token = await getToken(config.resources.gatewayApi.scopes)
const completeHeader = {
headers: {
...headers,
authorization:
token && token.accessToken ? `Bearer ${token.accessToken}` : '',
} as Express.Request,
}
console.log('accessToken: ', completeHeader.headers.authorization)
return completeHeader
})
Which generates the following TS error:
Property 'authorization' does not exist on type 'Request'.
This comes from trying to access completeHeader.headers.authorization. The property authorization is indeed not available on the Express.request interface. It's strange that TypeScript can't infere the type from the literal object, which clearly is of type string. When not defining the type as Express.Request an error is thrown about an unsafe any assignment.
Is it required to create a new TS interface just for this one field? Or are we using an incorrect type? The field authorization looks to be like a commonly used field for sending tokens.
The reason is because you're coercing completeHeader.headers into the Express.Request type. The coerced type overrides the inferred type.
What you can do, is expand that coerced type by doing the following:
as Express.Request & { authorization: string }
or you could create an entirely new type:
type AuthorizedRequest = Express.Request & { authorization: string };
...
as AuthorizedRequest
in my case, I needed to add user & I got error in headers with authorization(req.headers.authorization), me resolve was:
Case 1:
1.1. Where was error(req.headers.authorization), but before i had got similar error but with user:
import { IAuthRequest } from "./../types/user.type";
const checkAuth =
() => async (req: IAuthRequest, res: Response, next: NextFunction) => {
try {
//2. Second i got error here(main problem)
//i got if, i set <req:IRequestUser> for resolve
//problem with <req.user>: Property 'authorization'
//does not exist on type 'Headers'.
//And you need to change <req: IAuthRequest>, and
//resolve problems
if (!req.headers.authorization) throw new Error("Please log in");
const token = req.headers.authorization.split(" ")[1];
if (!process.env.SECRET_ACCESS_TOKEN)
throw new Error("Please create <SECRET_ACCESS_TOKEN> in .env file");
const { decoded, expired } = Jwt.verifyJwtToken(
token,
process.env.SECRET_ACCESS_TOKEN
);
if (expired) return res.status(401).send("Token has been expired");
//1. first error here
//before(Property 'authorization' does not exist on
//type 'Headers'.) i have got error here(Property
//'user' does not exist on type 'Request'.), if
//<req: Request>, you can try resolve this problem
//<req: IRequestUser> and after this, i got error
//with req.headers.authorization (see <2. Second i
//got error ...>, code above)
req.user = decoded;
next();
} catch (err) {
return res.status(400).send(err);
}
};
1.2. In folder named like "types", i have created file <user.type.ts>
and added:
export interface IUserData {
_id: string;
email: string;
username: string;
}
export interface IRequestUser extends Request {
user: IUserData;
}
export type IAuthRequest = IRequestUser & {
headers: { authorization: string };
};
You need just delete comments and code above will work correctly, comment only for understanding what was in code before error, and how i resolve this problems
Case 2:
after a while I found an even easier way:
import { IAuthRequest } from "./../types/user.type";
const checkAuth =
() => async (req: Request, res: Response, next: NextFunction) => {
try {
req as IAuthRequest;
//your code...
next();
} catch (err) {
return res.status(400).send(err);
}
};
i hope that maybe it will help to someone

Error while subscribing from http request angular

I'm working on the test driven angular app. (Don't ask why, That is how client wants)
Below is the spec which I can't modify or edit.
it('should get results', fakeAsync(
inject(
[XHRBackend, NewsService ],
(mockBackend: MockBackend, newsService: NewsService) => {
const expectedUrl = 'https://api.nytimes.com/svc/topstories/v2/home.json?api-key=315a5a51483b469a918246dc2753b339';
mockBackend.connections.subscribe((connection : MockConnection) => {
expect(connection.request.method).toBe(RequestMethod.Get);
expect(connection.request.url).toBe(expectedUrl);
connection.mockRespond(new Response(
new ResponseOptions({ body: mockResponse })
));
});
newsService.getSectionNews('home')
.subscribe( (res: any) => {
expect(res).toEqual(mockResponse);
});
})
));
So based on the spec, I need to write my front end code.
So this is what I've written,
import { Http } from '#angular/http';
constructor(private http: Http) {}
getSectionNews(sectionName: string): any {
// fetch news of that sectionName
// return this.mockResponse;
const expectedUrl = 'https://api.nytimes.com/svc/topstories/v2/home.json?api-key=315a5a51483b469a918246dc2753b339';
return this.http.get(expectedUrl).subscribe(res => res);
}
But while running the test case, I'm getting this error:
TypeError: newsService.getSectionNews(...).subscribe is not a function
please tell me what I'm doing wrong here.
I wanted to pass the test case.
UPDATE
After updating my service spec.
getSectionNews(sectionName: string): Observable<any> {
const expectedUrl = `https://api.nytimes.com/svc/topstories/v2/${sectionName}.json?api-key=315a5a51483b469a918246dc2753b339`;
return this.http.get(expectedUrl);
}
Now I'm getting this below error,
Expected Response with status: null null for URL: null to equal
Objectt({ status: 'OK', copyright: 'C ...

Cannot make a simple http GET call in Angular2

I am trying to make a simple http GET request from my Angular2 app:
this.http.get("https://mybaseurl.com/hello")
.map(res => res.json())
.subscribe(
function(response) { console.log("Success Response" + response)},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
The Node.js server is configured this way:
app.get('/hello', function(req, res) {
res.send("hellow world");
});
When I make the call I keep getting this error:
caused by: unable to parse url 'https://mybaseurl.com/hello'; original error: Cannot read property 'split' of undefined
at InMemoryBackendService.parseUrl (in-memory-backend.service.ts:518)
at InMemoryBackendService.handleRequest (in-memory-backend.service.ts:279)
at InMemoryBackendService.createConnection (in-memory-backend.service.ts:240)
Any idea what am I doing wrong?
edit: pasting the entire class code:
import {Component} from '#angular/core';
import {Auth} from './auth.service';
import {AuthHttp} from 'angular2-jwt';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'ping',
templateUrl: 'app/ping.template.html'
})
export class ApiService {
API_URL: string = 'https://myapp.herokuapp.com';
message: string;
constructor(private auth: Auth, private http: Http, private authHttp: AuthHttp) {}
public ping() {
this.http.get(`${this.API_URL}/hello`)
.map(res => res.json())
.subscribe((response) => {
console.log("Success Response" + response)
},
(error) => { console.log("Error happened" + error)},
() => { console.log("the subscription is completed")}
);
}
}
=====>
This looks like a HUGE bug in Angular2 - all http requests return null, or an error message describing it is not in the required pattern.
I someone has a working demo of HTTP GET I would love to see
It looks like using InMemoryWebApiModule.forRoot(InMemoryDataService) in #NgModule simultaneously with Http.get causes uncovered urls to return null and error.
Setting it this way worked for me:
InMemoryWebApiModule.forRoot(InMemoryDataService, {passThruUnknownUrl: true})
Maybe it is beacause of your answer from server - you send string to client, but in map function you try to call res.json(). Can you comment map function call?
Check by using arrow function for success and error as below :
this.http.get("https://mybaseurl.com/hello")
.map(res => res.json())
.subscribe((response) => { console.log("Success Response" + response)},
(error) => { console.log("Error happened" + error)},
() => { console.log("the subscription is completed")}
);

Angular 2 JSONP injected script did not invoke callback error

I am running app on localhost://3000 with npm server
Services file:
import {Injectable} from "#angular/core";
import {Jsonp} from "#angular/http";
import 'rxjs/add/operator/map';
#Injectable()
export class futScoreService{
constructor(private _jsonp:Jsonp){}
getCompetitions(){
let queryString ='?callback=JSONP_CALLBACK';
return this._jsonp.get('http://api.football-data.org/v1/competitions/' + queryString,{method: 'Get'})
.map((res) => res.json());
}
}
Component file:
ngOnInit(){
this._futScoreService.getCompetitions().subscribe(
(comp)=>{
console.log(comp);
},
(err)=>{
console.log(err);
}
);
}
And I'm getting this error in console console-error
and on network tab I get object from API network-tab
Ok solution was making get request with http module and providing header with get request. Header part was main reason why it was failing.
let headers = new Headers({'X-Mashape-Key':'Ns0SkjyRRomshq3PgEnGoz2Zkc71p1CYnWajsnphGctvrGt46W'});
headers.append( 'Accept', 'application/json');
return this._http.get("http://api.football-data.org/v1/competitions/",{
headers: headers
})
.map((res) => res.json());
Angular is replacing JSONP_CALLBACK with
__ng_jsonp____req0_finished
but it should be
__ng_jsonp__.__req0.finished
Inspect your Network response. If you see __ng_jsonp____req0_finished({...json object...}) this is the problem.
Also, some services have different requirements for the callback query string parameter, which proves to be nasty because the error is exactly the same. I was using &callback=__ng_jsonp__.__req0.finished with MailChimp which produced the same error but the response had only a json object and no callback function. This is because MailChimp's spec is to use &c= instead of &callback=
When hardcoding the Jsonp callback (re: JSONP_CALLBACK issue) you need to account for the number of calls made, as Angular persists the state of each call. An example of what I'm doing for Mailchimp:
addEmailToList(email: string, listId: string, jsonpCalls: number, callback: any) {
const cbJsonp = '__ng_jsonp__.__req' + jsonpCalls + '.finished';
let url = [
'http://',
host,
'/subscribe',
'/post-json',
].join('');
let queryParams: URLSearchParams = new URLSearchParams();
queryParams.set('u', Config.MAILCHIMP_API_KEY);
queryParams.set('id', listId);
queryParams.set('EMAIL', email);
queryParams.set('c', cbJsonp); // non-standard; varies by service; usually 'callback'
...
}
this._InstUrl = "your url";
let params1 = new URLSearchParams();
//params.set('search', term); // the user's search value
//params.set('action', 'opensearch');
params1.set('format', 'json');
//params1.set('callback', "ng_jsonp.__req0.finished");
params1.set('callback', "JSONP_CALLBACK");
return this._jsonp
.get(this._InstUrl, { search: params1 })
.map(response => { debugger; this.Result = response.json().data })
.subscribe(
(data) => {
debugger
console.log(this.Result);
},
(error) => {
debugger
console.log(error);
});

Categories