Trim text from HTTP JSON response - javascript

Angular/JavaScript amateur here, working on my first project using this framework. I have a Component that uses a Service which performs a GET request to a given URL.
Component:
#Component({
selector: 'jive-list',
templateUrl: './jivelist.component.html',
styleUrls: ['./jivelist.component.css']
})
export class JiveListComponent implements OnInit {
JiveLists: String[]; //placeholder
constructor(private JiveListService: JiveListService) { }
getJiveList(): void {
console.log("test");
this.JiveListService.getData().subscribe(
data => console.log(JSON.stringify(data)));
}
ngOnInit() {
this.getJiveList();
//console.log(this.JiveLists) //placeholder
}
}
Service:
#Injectable()
export class JiveListService {
API_URL = environment.JIVEAPIURL //can append endpoints where needed
constructor (public http: HttpClient) {
console.log("constructor runs");
}
getData(): Observable<any> {
return this.http.get<any>(this.API_URL).map((res) => res);
}
}
The API URL is a local file for now, located at './assets/data/data.json'
This code essentially gets a JSON from the URL and logs it in the console. When the file is purely JSON, this works with no issues. However, the JSON that will be provided in production always starts with a string.
JSON sample:
throw 'allowIllegalResourceCall is false.';
{
"id" : "123456",
"resources" : {
//rest of the JSON
I have tried the two solutions recommended in this article, but none of them have changed my result.
Example (attempted) solution:
getData(): Observable<any> {
return this.http.get<any>(this.API_URL).map((res) => res.substring(res.indexOf('{')));
}
My error message:
SyntaxError: Unexpected token h in JSON at position 1 at Object.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.bundle.js:43048:37) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2513:31) at Object.onInvokeTask (http://localhost:4200/vendor.bundle.js:75481:33) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2512:36) at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.bundle.js:2280:47) at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.bundle.js:2587:34) at invokeTask (http://localhost:4200/polyfills.bundle.js:3628:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.bundle.js:3654:17)
Any ideas that would help me fix this issue would be appreciated. I am using Angular 4.2.4, and using #Angular/common/HttpClientModule as my HTTP handler.

Could you try this instead then,
the getData() method in service,
getData(): Observable<any> {
return this.http.get<any>(this.API_URL);
}
the getJiveList() in component,
getJiveList(): void {
console.log("test");
this.JiveListService.getData()
.subscribe(data => {
data = data.toString().substring(data.toString().indexOf('{'));
console.log(data);
});
}
If this doesn't work, then may be it is likely due to way we parse the data from the GET request.

The issue was found to come from the HttpClientModule's get method, which will automatically run json.parse() on the response if it is requesting a URL ending in .json. I was unable to find a simple fix for this on the front-end, instead I referred to a Spring API which would redirect my request and use a modified JSON-parsing method that trims the string from the file.

Related

Angular request redirect to URL after POST submission

I am new to Angular and following this tutorial to create a MailChimp submission form. I have replaced the list information & id and the tutorial with my own. On submission of the form, I want to redirect to a Thank You page, which was not shown in the tutorial.
When I submit user email to the list, I get a 200 response back from the server on my POST request.
However, I have two problems.
#1 The redirect does not navigate to the '/thanks' route. I'm not sure if this is the actual way this function should be used for navigation. I thought it would work similar to React's this.history.push. I got the basic idea for this function from this Stack Overflow question
subscribe-form-component.ts
export class SubscribeFormComponent implements OnInit {
subscribeData: any = <any>{};
constructor(
private subscribeService: SubscribeService,
private router: Router
) {}
ngOnInit() {}
onSuccess() {
this.router.navigate(['/thanks']);
}
subscribe(subscribeForm: NgForm) {
if (subscribeForm.invalid) {
return;
}
this.subscribeService.subscribeToList(this.subscribeData).subscribe({
complete: () => {this.subscribeData},
next: () => {this.onSuccess},
error: (err) => {
console.log('err', err);
},
});
}
}
However, in the console log console.log('err', err), though the submit form returns a 200 response from the sever, I did notice a JSONP error:
Error: JSONP injected script did not invoke callback.
message: "Http failure response for https://xxxxxxx.us11.list-manage.com/subscribe/post?u=afd1f3490xxxxxxxx7883fb&id=035xxxx952&f_id=009fa6e0f0&EMAIL=xxxxxx#icloud.com&c_afd1f34907923e052b17883fb_009fa6e0f0=&c=ng_jsonp_callback_0: 0 JSONP Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "JSONP Error"
url: "https://xxxxxx.us11.list-manage.com/subscribe/post?u=afd1f349xxxxxxx7883fb&id=035b97f952&f_id=009xxxxf0&EMAIL=xxxxx#icloud.com&c_afd1f34907923e052b17883fb_009fa6e0f0=&c=ng_jsonp_call
If my onSuccess navigation route function/syntax is correct, I'm assuming that the reason it is not redirecting is because of this error in the console.
subscribe.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class SubscribeService {
mailChimpEndpoint = 'https://xxxxxx.us11.list-manage.com/subscribe/post?u=afd1f3490xxxxxxxxxb&id=035b9xxxx52&f_id=009faxxxf0';
constructor(
private http: HttpClient,
private router: Router
) { }
subscribeToList(data: any) {
const params = new HttpParams()
.set('EMAIL', data.email)
.set('afd1f3490xxxxxxxxxxb_009fa6e0f0', '');
const mailChimpUrl = `${this.mailChimpEndpoint}&${params.toString()}`;
return this.http.jsonp(mailChimpUrl, 'c')
}
}
How do I fix this JSON P error and correctly redirect after submission?
By default, JSONP will cause the error that you are seeing when using the Angular HttpClient.
There is a HttpClientJsonpModule that can be used instead of the HttpClientModule, and it does support JSONP.
Documentation is at https://angular.io/api/common/http/HttpClientJsonpModule

I want to get my Graph API token but I got an error, I'm making a POST request with HttpServices. I'm getting a 400 status code. I'm using NestJS

**This is my code when I'm creating the class and the method:**
#Injectable()
export class MicrosoftGraph {
constructor(private httpService: HttpService) {}
getMicrosoftGraphToken() {
const data = {
client_id: 'myclientid',
scope: 'https://graph.microsoft.com/.default',
client_secret: 'myclientsecret',
grant_type: 'client_credentials'
}
const url =
'https://login.microsoftonline.com/mytenantid/oauth2/v2.0/token';
const response = this.httpService.post(url, data).pipe(
tap((resp) => console.log(resp)),
map((resp) => resp.data),
tap((data) => console.log(data)),
);
console.log(response);
return response;
}
}
This is the part of the controller:
#Controller('user')
export class UsersController {
constructor(private readonly microsoftGraph: MicrosoftGraph) {}
#Get('hola')
intento(#Res() res: Response, #Req() req: Request){
return this.microsoftGraph.getMicrosoftGraphToken();
}
}
And this is the error I'm getting:
Observable {
source: Observable {
source: Observable {
source: [Observable],
operator: [Function (anonymous)]
},
operator: [Function (anonymous)]
},
operator: [Function (anonymous)]
}
[Nest] 19464 - 08/30/2022, 8:05:31 AM ERROR [ExceptionsHandler] Request failed with status code 400
[Nest] 19464 - 08/30/2022, 8:05:31 AM ERROR [ExceptionsHandler] undefined
I'm trying to get this token to be able to make a function where I can pull a list of users in my company, please help and thanks
Not sure if you solved this already, but the problem is in your URL. You have hardcoded the tenantId part. So instead of:
const url = 'https://login.microsoftonline.com/mytenantid/oauth2/v2.0/token';
It should probably be something like this:
const graphTenantId = `1234-abcd-etc-etc`;
const url =
`https://login.microsoftonline.com/${graphTenantId}/oauth2/v2.0/token`;
The way you are currently doing it, is that you are trying to get the tenant with ID "mytenantid".
Also, since you are using NestJS, I would advise you to use the .env file to save the data that you now put in your "data" constant and similar to the tenant_id that you still need to add. This of course only applies when these values are set in stone. The NestJS documentation has a great summary on how to do this.
If you have dynamic data in regards to the Graph API (so you would have clients that would connect through your NestJS application), you can probably best make a GraphConfiguration object which you then get using a service (that's the way I did it).
Hope this helps you!

why Httpclient not working in angular 5?

I am trying to get data from the server and show in dropdown .but I am getting an error in while fetching data from the server.
here is my code
https://stackblitz.com/edit/angular-xsydti
ngOnInit(){
console.log('init')
this.dropdownService.getBankData().subscribe((res)=>{
console.log(res);
})
}
service code
getBankData(){
return this.http.get<DropDownModel[]>(`{this.DOMAIN_URL}`)
}
You need to use https instead of http, i have made the changes here
#Injectable()
export class DropDownService {
private DOMAIN_URL ='https://biz.timesofindia.indiatimes.com/bankifsc/getlist'
constructor(private http:HttpClient) { }
getBankData(){
return this.http.get<any[]>(this.DOMAIN_URL)
}
}
also access res.data to get your data
DEMO

Inject $http into Tour of Heroes Component

I have the Tour of Heroes app running, but I want to extend it to make ajax calls.
I have a WebAPI service that serves up the data (CORS enabled) and have proven it w/ a silly little non Angular client using JQuery $.post and $GetJson ... All was going well...
Here is my hero-details.component.ts file
(happy to include any others that may help...)
import {Component , Input, OnInit } from '#angular/core';
import { ActivatedRoute, Params } from '#angular/router';
import { Location } from '#angular/common';
import { HttpModule } from '#angular/http';
import 'rxjs/add/operator/switchMap';
import { Hero } from './hero';
import { HeroService } from './hero.service';
#Component({
selector: 'hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls : ['./hero-detail.component.css']
})
export class HeroDetailComponent { // implements OnInit {
#Input() hero: Hero;
powers = ['Really Smart', 'Super Flexible', 'Weather Changer'];
submitted = false;
constructor(
private heroService: HeroService,
private route: ActivatedRoute,
private location: Location,
$http //**--LINE OF INTEREST #2**
) { }
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id']))
}
save(): void {
this.heroService.update(this.hero)
.then(() => this.goBack());
}
goBack(): void {
this.location.back();
}
onSubmit() { this.submitted = true; }
callService( ) {
var uri = 'http://localhost:61212/api/heros';
//**// LINE OF INTEREST #1**
$http({
method: 'GET',
url: uri
}).then(function () { alert('success'); }, function () { alert('fail');});
};
}
If I try to compile I get
TS2304: Cannot find '$http'
I can comment the $HTTP call (Line of Interest #1 ) and it compiles, it runs and i do enter the function and hit a breakpoint where i declare and assign the variable "uri". So I am reasonably sure I have the problem isolated.
So I believe, based on hours of googling, that I need to DI the $http object into this component
But when I pass $http into the constructor (LINE OF INTEREST #2) I get the following error when I try to compile
TS7006 Parameter '$http' implicitly has an 'any' type
I have googled this so much Larry and Sergy have asked me to knock it off.
What I have found is $http being passed into controllers, maybe Im missing something, but I can not seem to translate those articles into something that works for this.
1) Am I right that injecting the $http object is what needs to be done
2) What is the syntax?
when I was googling , i was just googling angular and most the articles were for angular1. Thats why I was seeing answers that involved controllers, etc.
angular2 is much different. If you are trying to get off the ground, try searching angular2 instead. at least the articles you run across will be relevant.
if you are using visual studio.. here is a nice link to get you started...
https://jonhilton.net/2016/12/01/fast-track-your-angular-2-and-net-core-web-app-development/

SyntaxError: Unexpected token O with every POST request, not parsing

I'm using Angular and ES6 to send data to Spring Boot RESTful API.
class PostsService {
constructor($http) {
this.getAllPosts = () => {
return $http.get('http://localhost:8080/posts');
};
this.addPost = () => {
let data = {content : "BBB", date : "55.55.5555"};
return $http.post('http://localhost:8080/newPost', data);
};
}
}
PostsService.$inject = ['$http'];
export default angular
.module('blog.Posts')
.service('PostsService', PostsService);
GET request works without any problems.
POST totally sends the data (REST API gets it and puts it into the database as it should), on the other hand, generates this silly, and completely weird error:
SyntaxError: Unexpected token O
at Object.parse (native)
at fromJson (http://localhost:4000/build/bundle.js:1351:15)
at defaultHttpResponseTransform (http://localhost:4000/build/bundle.js:10202:17)
at http://localhost:4000/build/bundle.js:10293:13
at forEach (http://localhost:4000/build/bundle.js:390:21)
at transformData (http://localhost:4000/build/bundle.js:10292:4)
at transformResponse (http://localhost:4000/build/bundle.js:11065:22)
at processQueue (http://localhost:4000/build/bundle.js:15621:29)
at http://localhost:4000/build/bundle.js:15637:28
at Scope.$eval (http://localhost:4000/build/bundle.js:16889:29)
I think it's worth to point out, that I'm using webpack, and no JSON parsing is done whatsoever (excluding angular http parsing, that I have no information of).
The thing was - it is somehow required, that backend returns JSON. So I changed:
#RequestMapping(path="/newPost", method= RequestMethod.POST)
public #ResponseBody() String createPost(#RequestBody Post payload) {
repository.save(payload);
return "OK";
}
to:
#RequestMapping(path="/newPost", method= RequestMethod.POST)
public #ResponseBody() List<String> createPost(#RequestBody Post payload) {
repository.save(payload);
List<String> list = new ArrayList<String>();
list.add("OK");
return list;
}
And it worked. Cheers doods!

Categories

Resources