This question already has answers here:
Angular 2 http get not getting
(4 answers)
Closed 3 years ago.
I'm trying top send a post request on angular and im pretty sure that the problem is not in the backend side since i used postman and it worked on postman.
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Injectable()
export class ConHttpService {
private headers: HttpHeaders;
private accessPointUrl: string = 'https://localhost:44340/api/contact';
constructor(private http: HttpClient) {
this.headers = new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'});
}
public addcon(payload) {
console.log("hi") //prints hi
console.log(this.accessPointUrl, payload, {headers: this.headers}) //gives a link that take me to a url full of json of targeted database but without my added object
return this.http.post(this.accessPointUrl, payload, {headers: this.headers});
}
}
in the sending component:
onSubmit(){
console.log(this.contactForm.value)
this.conhttp.addcon(this.contactForm.value)
}
HttpClient.post() returns an observable. In order to invoke the operation, you need to call subscribe() on that observable.
this.conhttp
.addcon(this.contactForm.value)
.subscribe()
Related
I'm using Angular 9 in my web app. I'm using a lot of services to connect to a web service. Sometimes a lot of identical requests are sent to a service. Maybe when a user click on a button repeatedly.
I want to cancel previews incomplete requests for all of my services. What's the best solution? (Maybe using RXJS)
This is one of my service functions:
constructor(private http: HttpClient) {}
getList(options?: ApiListOptions) {
return this.http.post<ApiResponse<UserGet[]>>(
environment.apiRoot + 'user/list',
options,
{ headers: this.headers() }
);
}
Thanks
Please try below with takeUntil rxjs operator you will be able to do the same.
export class YourComponent {
protected ngUnsubscribe: Subject<void> = new Subject<void>();
[...]
public httpGet(): void {
this.http.get()
.takeUntil(this.ngUnsubscribe)
.subscribe( (data) => { ... })
}
public ngOnDestroy(): void {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
For your specific case, like frequent button clicks, you can use switchMap() combine with debounceTime() to limit the frequency of action and http calls. You can use Subject for action trigger instead of component method
<button click="getList.next()">click</button>
getList=new Subject()
getList.pipe(debounceTime(2000),switchMap(()=>
this.http.post<ApiResponse<UserGet[]>>(
environment.apiRoot + 'user/list',
options,
{ headers: this.headers() }
);
)).subscribe()
My question is very simple... How can make an Post HttpRequest with params in angular 4. I could not find an example ... the examples I find are using HttpClient, but it's not what I need
Without XHR or fetch (aka AJAX), you're not able to instruct the browser to make an HTTP POST request. By navigating to some URL, the browser makes a HTTP GET request.
If you want to send an HTTP POST request directly from the browser, you'll need to use XHR/fetch.
Circling back to this, although I managed to create a test with a get method using the HttpRequest class I was having trouble with using the POST method. Instead I used the HttpModule from #angular/http and the accompanying classes. Then I tried adding an e.preventDefault. Try that and see if it works for you. Additionally you may need to use pure JS methods here.
in AppComonent
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from '#angular/http';
import { Component, OnInit } from "#angular/core";
export class AppComonent implements OnInit {
dataBody =JSON.stringify({
title: "foo",
body: "bar",
userId: 1
});
headers;
requestOptions;
requestMethod;
Response;
constructor(private http: Http) {}
ngOnInit(
) {
}
onPreventDefault(e){
e.preventDefault();
}
onPostData(){
return this.postRequest('https://jsonplaceholder.typicode.com/posts', this.dataBody);
}
postRequest(url,data) {
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.requestOptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: this.headers,
body: data
});
return this.http.request(new Request(this.requestOptions))
.subscribe((res: Response) => {
if (res) {
console.log(res);
}
});
}
}
in module.ts
import { HttpModule } from '#angular/http';
imports: [HttpModule];
in app-component.html
<form (ngSubmit)="onPostData()" (submit)="onPreventDefault($event)" target="_blank" action="http://localhost:3000/api/users" >
<button type="submit" >Submit</button>
</form>
in app.module.ts
import { HttpClientModule } '#angular/common/http';
#NgModule ({
imports: [HttpClientModule]
})
in app.component.ts
import { HttpClient } from '#angular/common/http';
export class AppComponent {
constructor(private http: HttpClient) {
this.http.post('http://someurl/endpoint', {postData1: 'avb', postdat2: 'xyx}).subscribe(res => console.log(res), error => console.log(error));
}
}
import { Injectable } from '#angular/core';
import {StockComponent} from './stock.component';
import {AppComponent} from '../app.component';
import {Http, Response} from '#angular/http';
import './rxjs-operators';
#Injectable()
export class StockApiService {
symbol: string
public stocks = [
];
purchased = ["",""];
constructor(private http: Http) {
http.get('http://localhost:8000/stock/' + this.symbol)
.map(res => res.json())
//parameter //key
// .subscribe(stockInfo => this.stocks.push(stockInfo))
.subscribe(stockInfo => console.log(stockInfo))
}
getStockInfo(symbol : string) {
this.purchased.push(symbol);
let stockLink: string = 'http://localhost:8000/stock/' + symbol;
//writing logic for get stock search bar
}
//retrieves stock from array
getStock (symbol : string) {
for (var i = 0; i < this.stocks.length; i++) {
if (symbol.toLowerCase() === this.stocks[i].symbol.toLowerCase()) {
return this.stocks[i];
}
}
}
}
obviously there are a lot more files but this is the service i'm working in. also new to angular2 so let me explain what i know is going on and what i'm doing.
I'm creating a stock market simulator and i'm trying to get the data from google to my front end of angular2. So i did some really hacky stuff and I have a second node server with cors getting data from google, and I have my angular2 sending a get request to my server so I can display it on the front end. I realized that google is not returning to me JSON and rather it is returning to me HTML? or just javascript because it looks like an array.
So my i'm taking this link http://finance.google.com/finance/info?client=ig&q=' and I have an input field which is going to take the value (symbol) inputted attach it onto this url, then I want to get the data I need through what google returns to me.
So if anyone can help me, im new to angular2 and this is a lot to handle
I am using angular2 http.post in the following service:
import {Injectable, Inject} from 'angular2/core'
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';
import 'rxjs/add/operator/map';
//Globals
const URL : string = 'http://myurl.com/listings';
#Injectable()
export class ListingsService {
//Constructor
constructor(public http: Http) {}
postListing(data) {
this.http.post(URL, data).map(res => res.json())
}
}
The issue is that I am only allowed to post data as a string inside http.post, where as I need to pass in an Object.
One way of doing this is using JSON.stringify for making a string of object and then JSON.parse on the server side.
Probably you need to set Content-Type in your header. You can set default header as follows.
class MyOptions extends RequestOptions {
constructor() {
super({
headers: new Headers({
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json'
})
});
}
}
bootstrap(AppComponent, [
...,
provide(RequestOptions, {useClass: MyOptions})
]);
as binariedMe mentioned, JSON.stringify will do what you want.
If you want to send binary data maybe you want to look into BSON: https://github.com/mongodb/js-bson
I have a service class that should call an api and return the results:
import {Component, View} from 'angular2/angular2';
import { Inject} from 'angular2/di';
import {Http} from 'angular2/http';
var httpMap = new WeakMap<ScheduleService, Http>();
export class ScheduleService {
meetings: Array<any>;
http: any;
constructor(#Inject(Http) http:Http){
httpMap.set(this, http);
this.http = http;
//http.get('/api/sample')
// .map(response => response.json())
// .subscribe(data => {
// this.serverData = data;
// });
}
getMeetings(){
var path = '/api/meetings/';
return httpMap.get(this).get(path);
}
}
The service class is being called and injected correctly. The issue I am having is that when ever I call the getMeetings method it never makes the request to /api/meetings. If you guys notice in the constructor there is a get request to /api/sample that works perfectly if I uncomment it and run the program I check my network tab and I can see the request was made.
Looks like http.get(path) doesn't send off a request unless you call http.get(path).subscribe(); even if you don't do anything with the response.
Plunker: https://plnkr.co/edit/b1fxoIUy31EHTC84U344?p=preview
In the Plunker, open the network view in the console and click the With Subscribe / Without Subscribe buttons for comparison.