why Httpclient not working in angular 5? - javascript

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

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

How can I recive a response data from an http request in Angular?

I want to read a response from a get http request, my server is in Javascript and the part of the where I send a response is:
app.get('/getReport',function(req,res) {
try {
const data=fs.readFileSync('./report.txt', 'utf8')
res.end(data)
}
catch (err) {
res.end("File not found")
}
})
If if I use Postman I can see the content of the report file.
I want to read this text on my Angular front-end so I create this function in my home.service.ts:
public getReport(){
return this.http.get<any>(this.url+'/getReport').subscribe(data => {
this.value = data;})
}
It doesn't work. what can I do to read my content correctly?
Check your setup. You have to import some modules before get http requests:
#NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],...
In order to recive any response, you have to start a communication with your API/server subscribing to the 'getReport' method.
HOW CAN YOU DO THAT?
You have that method in your home.service.ts.
Inject that service in the component where you want to load your report (i.e 'home-component'):
// NOTE: Fit all the paths to your specific system
...
import { HomeService } from '../services/home.service';
...
#Component({
selector: 'app-home-component',
templateUrl: './home-component.html',
styleUrls: ['./home-component.scss'],
})
export class HomeComponent {
public report;
constructor(
...
private homeService: HomeService,
...
) {}
Subscribe to the observable 'getReport' method of homeService, and get the desired data.
For instance, change the constructor like this:
constructor(
...
private homeService: HomeService,
...
) {
this.homeService.getReport
.subscribe((_response) => {
console.log(_response);
this.report = _response;
alert(this.report);
});
}

how to get data seesion id and all from external url given, which not from my app(routing) in angular 6

Url: https://admin/workadd/cust_session?sessionId=1500c980954d7a81e6c428a16d8c25&srId=SR1234&custId=cust12345&custName=sam
This url is external given by backend to me, i need to fetch the data from url like session id, srid and all,
Whenever user clicks on this link it should open in my app and fetch details from url, my app in angular 6 using
import { ActivatedRoute, Router } from '#angular/router';
export class AppComponent{
public session;
constructor(private activatedRoute: ActivatedRoute){
this.activatedRoute.queryParams.subscribe(params =>{
this.session = params['sessionId'];
console.log("SessionId ",this.session)
});
}
}

Trim text from HTTP JSON response

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.

Angular 2 app base initialization

How can I make basic initialization of my data in app. For example if user logged in and press F5 I need to request current user data from server before all queries starts like get user order etc. In Angular 1 we have .run() directive for this case. How can I solve this problem?
There are several ways to do that:
You could execute some requests before bootstrapping your Angular2 application. Such first requests could rely what you save into the local / session storage.
var injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
var http = injector.get(Http);
http.get('/userdetails').map(res => res.json())
.subscribe(data => {
bootstrap(AppComponent, [
HTTP_PROVIDERS
provide('userDetails', { useValue: data })
]);
});
See this question for more details:
How to bootstrap an Angular 2 application asynchronously
You could extend the HTTP request to transparently get these data when requests are actually executed. This would be a lazy approach.
#Injectable()
export class CustomHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, userDetailsService: UserDetailsService) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
console.log('request...');
return this.userDetailsService.getUserDetails().flatMap((userDetails) => {
return super.request(url, options);
});
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
console.log('get...');
return this.userDetailsService.getUserDetails().flatMap((userDetails) => {
return super.get(url, options);
});
}
}
implement the UserDetailsDetails this way:
export class UserDetailsService {
constructor(private http:Http) {
}
getUserDetails() {
if (this.userDetails) {
return Observable.of(this.userDetails);
} else {
return this.http.get(...)
.map(...)
.do(data => {
this.userDetails = data;
// Store in local storage or session storage
});
}
}
and register this CustomHttp class this way:
bootstrap(AppComponent, [HTTP_PROVIDERS,
UserDetailsService,
new Provider(Http, {
useFactory: (backend: XHRBackend,
defaultOptions: RequestOptions,
userDetailsService: UserDetailsService) => new CustomHttp(backend, defaultOptions, userDetailsService),
deps: [XHRBackend, RequestOptions, UserDetailsService]
})
]);
See these questions for more details:
Angular 2 - How to get Observable.throw globally
Cache custom component content in ionic 2
Things could also be done at the level of the router outlet if you use routing. It's possible to implement a custom router-outlet that checks security / user details when a route is activated. I think that it's a little further from your need...
See this question for more details:
Angular 2 Cancelling Route Navigation on UnAuthenticate
You could fetch the current user data before you call Angular2's bootstrap(...)
You could also fire an event (using an Observable for example) to notify other that the logged-in user is now known and initiate further requests only after this event was received.

Categories

Resources