Send File from Angular to Nodejs - Cannot read property 'headers' of undefined - node.js

I'm having issues passing my data with a file to my nodejs backend. I'm currently using azure functions to run my nodejs code. Currently when I pass the data with file, I'm getting a Cannot read property 'headers' of undefined I'm adding the header in the options so I don't really understand why I'm getting the error.` Working with files is definitely one of my weaknesses so I appreciate any help!
import { Injectable, OnDestroy } from "#angular/core";
import { Subject, Observable } from "rxjs";
import {
HttpClient,
HttpParams,
HttpRequest,
HttpHeaders,
HttpEvent,
HttpEventType
} from "#angular/common/http";
import { map, takeUntil, switchMap } from "rxjs/operators";
import { Router } from "#angular/router";
import { environment } from 'src/environments/environment';
import { AuthService } from '../auth.service';
import { SendAppealModel } from './send-appeal.model';
#Injectable({ providedIn: "root" })
export class SubmitAppealService implements OnDestroy {
destroy = new Subject();
constructor(private http: HttpClient, private router: Router, private authService: AuthService) { }
ngOnDestroy() {
this.destroy.next();
this.destroy.complete();
}
submitAppeal(
username: string,
email: string,
file: File
) {
let form = new FormData();
form.append('file', file);
form.append('username', username);
form.append('email', email);
console.log("FILE OUTPUT");
console.log(file);
let headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = { headers: headers, reportProgress: true };
const api = environment.azure_function_url + `/PATCH-Send-Appeal`;
const req = new HttpRequest('PATCH', api, form, options);
return this.http.request(req)
.pipe(
map((res: HttpEvent<any>) => {
if (res.type === HttpEventType.Response) {
return res.body.id.toString();
} else if (res.type === HttpEventType.UploadProgress) {
// Compute and show the % done:
const UploadProgress = +Math.round((100 * res.loaded) / res.total);
return UploadProgress;
}
})
);
}
}
azure function
const multer = require('multer');
const upload = multer({ dest: 'public/uploads/' }).single('file');
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
upload();
console.log(req.file);
var filename = path.basename("../" + req.file.path);
console.log("filename");
console.log(req.file.destination);
console.log(__dirname);
var form = new formidable.IncomingForm();
console.log("form");
console.log(form);
context.res = {
status: 200,
headers: {
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PATCH, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Set-Cookie',
'Access-Control-Max-Age': '86400',
Vary: 'Accept-Encoding, Origin',
'Content-Type': 'application/json',
},
};
context.done();
};

I'm assuming you are getting that error because your headers aren't actually making it to your azure function.
Currently you have this:
let headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = { headers: headers, reportProgress: true };
You can't do that. headers.append doesn't do an in-place update. It returns a new HttpHeaders object. So, you actually need this:
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'multipart/form-data');
headers = headers.append('Accept', 'application/json');
let options = { headers: headers, reportProgress: true };
Per comments, I see one other thing that looks a little off to me. This may be part of the issue. Try updating your HTTP call to this:
const req = new HttpRequest('PATCH', api, form, options);
return this.http.patch(api, form, options)
.pipe(
map((res: HttpEvent<any>) => {
if (res.type === HttpEventType.Response) {
return res.body.id.toString();
} else if (res.type === HttpEventType.UploadProgress) {
// Compute and show the % done:
const UploadProgress = +Math.round((100 * res.loaded) / res.total);
return UploadProgress;
}
})
);
You might also set a breakpoint in your azure function on the first line to inspect the request object and make sure your HttpHeaders are making it in.

Related

Axios and Oauth1.0 - 'status: 400, Bad Request'

I'm new on Nodejs and all the modules related with Node. I've been trying to use axios for send a Oauth1.0 Autorization signature, but i'm getting: response: { status: 400, statusText: 'Bad Request', ...}
import { BASE_URL } from '../../../config/config.js';
import axios from 'axios';
import status from 'http-status';
import OAuth from 'oauth-1.0a';
import { createHmac } from 'crypto';
import dotenv from 'dotenv';
dotenv.config();
const CONSUMERKEY = process.env.consumer_key;
const CONSUMERSECRET = process.env.consumer_secret;
const TOKENKEY = process.env.access_token;
const TOKENSECRET = process.env.token_secret;
export const oauth = OAuth({
consumer: {
key: CONSUMERKEY,
secret: CONSUMERSECRET,
},
signature_method: 'HMAC-SHA1',
hash_function(base_string, key) {
return createHmac('sha1', key)
.update(base_string)
.digest('base64')
},
})
export const token = {
key: TOKENKEY,
secret: TOKENSECRET,
}
const doRequest = async (query) => {
const request_data = {
url: `${BASE_URL}`,
method: 'GET',
params: { q: `${query}` },
};
const authHeader = oauth.toHeader(oauth.authorize(request_data, token));
return await axios.get(request_data.url, request_data.params, { headers: authHeader });
};
const searchU = async (term) => {
return await doRequest(`${term}`);
};
export const userS = async (req, res, next) => {
try {
const { query } = req;
const { data } = await searchU(query.q);
const string = JSON.stringify(data);
const Rs = JSON.parse(string);
const response = {
code: 1,
message: 'sucess',
response: Rs
};
res.status(status.OK).send(response);
} catch (error) {
next(error);
if (error.response){
console.log("Response: ");
console.log(error.response);
} else if(error.request){
console.log("Request: ");
console.log(error.request)
} else if(error.message){
console.log("Message: ");
console.log(error.message)
}
}
};
I've been also trying the solution given On this post: but there's no way I can make this work, no idea what i could be doing wron...
When i try the following code (see below), using Request module (which is deprecated) works well, but I really need to do it with Axios...
const request_data = {
url: `${BASE_URL}`,
method: 'GET',
params: { q: `${query}` },
};
const authHeader = oauth.toHeader(oauth.authorize(request_data, token));
request(
{
url: request_data.url,
method: request_data.method,
form: request_data.params,
headers: authHeader,
},
function(error, response, body) {
console.log(JSON.parse(body));
}
)
Any thoughts on what I'm doing wrong on this?? Thank you very much!!
Refer to the following link for the Request Config for Axios. I believe you need to have the query params after the header in the axios.get()
Axios Request Config
Try, the following and see how it goes:-
return await axios.get(request_data.url, { headers: authHeader }, request_data.params);

NestJs : How to implement node.js Post and Get logic in NestJs

I'm trying to implement node.js Spotify Authorization flow in NestJs.
But HttpService Post and Get functions doesn't work as in node.js.
Node.js working example:
var request = require('request'); // "Request" library
app.get('/callback', function(req, res) {
var authOptions = {
url: 'https://some-url.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (Buffer.from(client_id + ':' + client_secret).toString('base64'))
},
json: true
};
// I'm trying to implement this post in NestJS
request.post(authOptions, function(error, response, body) {
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, response, body) {
console.log(body);
});
}
I'm using HttpService Post method in NestJS
and that doesn't work:
constructor(private httpService: HttpService) {}
#Get('callback')
callback(#Request() req, #Res() res): any {
let code = req.query.code || null;
const url = 'https://some-url.com/api/token';
const form = {
code: code,
redirect_uri: this.redirect_uri,
grant_type: 'authorization_code'
}
const headers = {
'Authorization': 'Basic ' + (Buffer.from(this.client_id + ':' + this.client_secret))
}
// doesn't work
this.httpService.post( url, form, { headers: headers }).pipe(
map((response) => {
console.log(response);
}),
);
}
In NestJS, you do not need to send req, res object to your function parameter. Nest Js provide build-in decorator for req.body, req.query and req.param as #Body, #Query, and #Param. I write down to call post method and get method. You can also use put, patch, delete, and other methods. Please make a data transfer object file in your module.
for further reference, you can check this: https://docs.nestjs.com/controllers
export class yourController {
constructor(private readonly httpService: HttpService) {}
#Post('your-route-name')
public postMethod(#Body() yourDTO: YourDTOClass): Promise<interface> {
try {
return this.httpService.method(yourDTO);
} catch (err) {
throw new HttpException(err, err.status || HttpStatus.BAD_REQUEST);
}
}
#Get('your-route-name')
find(#Query() query: QueryDTO): Promise<interface> {
try {
return this.httpService.methodName(query);
} catch (err) {
throw new HttpException(err, err.status || HttpStatus.BAD_REQUEST);
}
}
}
You should put return before this.httpService.post(...). Normally you would have to subscribe to the Observable returned by the post method but NestJS handles this for you through the #Get() decorator.
You should prefix your controller with "async" and use "await" followed by "toPromise()"...
constructor(private httpService: HttpService) {}
#Get('callback')
async callback(#Request() req, #Res() res): any {
// ... remaining code here
const response =
await this.httpService.post(url, form, { headers: headers }).toPromise();
return response;
}
Add this imports to the controller:
import { Observable } from 'rxjs';
import { take, tap, map } from 'rxjs/operators';
Then try this:
constructor(private httpService: HttpService) {}
#Get('callback')
callback(#Request() req, #Res() res): Observable<any> {
let code = req.query.code || null;
const url = 'https://some-url.com/api/token';
const form = {
code: code,
redirect_uri: this.redirect_uri,
grant_type: 'authorization_code'
}
const headers = {
'Authorization': 'Basic ' + (Buffer.from(this.client_id + ':' +
this.client_secret))
}
return this.httpService.post( url, form, { headers: headers }).pipe(
// Take first result to complete the observable..
take(1),
// [OPTIONAL] Some debug log to see the response.
tap((response: { data: any }) => {
console.log(`Response: ${JSON.stringify(response.data)}`);
})
// Map the response object to just return its data.
map((response: { data: any }) => response.data),
);
}

How to pass parameters in headers

I need to call an API from my Angular Node application.For that i have to pass username and password along with header request.How to pass parameters?
I tried below code
From Angular service,
checkUserApi(url: string): Observable<any> {
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json')
.set('userName','prismtest')
.set('password','12345678');
return this.http.post('/upload/checkUserApi/', { headers })
.map((response: Response) => {
console.log(response);
return response;
})
}
In Node,
router.post('/checkUserApi',function(req,res,next){
var proxyUrl = 'http://cors-anywhere.herokuapp.com/';
Request.post({
"headers": { "userName": "prismtest","password":"12345678" },
"url": proxyUrl+"https://example.com",
"body": {}
}, (error, response, body) => {
if(error) {
return console.log(error);
}
res.send(response);
});
});
You can pass the form parameters as the second attribute to post request:
checkUserApi(url: string): Observable<any> {
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
return this.http.post('/upload/checkUserApi/', {username: 'prismtest', password: '123'}, { headers })
.map((response: Response) => {
console.log(response);
return response;
})
}
You can do it by using interceptors which is Angular Service.
this should be helpfull :How to pass a param to HttpInterceptor?
Can you try below code following
/* SERVICE ANGULAR*/
import {Injectable} from '#angular/core';
import {HttpClient, HttpHeaders} from '#angular/common/http';
import {Observable,of} from 'rxjs';
import { map,catchError } from 'rxjs/operators';
import {User} from '../_models';
const httpOptions = {
headers:new HttpHeaders({'Content-Type':'application/json'})
};
const API_URL = "http://localhost/app/api";
#Injectable({
providedIn:'root',
})
export class UserService{
constructor(private http:HttpClient){}
/**
* POST LOGIN USER
*/
login(user: any) {
return this.http.post<any>(API_URL+"/login", user,httpOptions)
.pipe(map(user => {
return user;
}));
}
}
/*NODEJS*/
/* 1) install $ npm install body-parser --save*/
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies */
/ POST http://localhost:8080/api/users
// parameters sent with
app.post('/api/login', function(req, res) {
var user_id = req.body.id;
var token = req.body.token;
var geo = req.body.geo;
res.send(user_id + ' ' + token + ' ' + geo);
});
Can you seen : Use ExpressJS to Get URL and POST Parameters
Login State Angular + Laravel
const headerOptions = {
headers : new HttpHeaders({
'Constent-Type' : 'application/json',
'Authorization : 'you token here'
})
}
http.post('you action', {body Params}, headerOptions, function(res){
console.log('your respose is ', res);
})

Angular 5 - Node/Express - not able to download pdf

am trying to download pdf file from local folder that structures like
assets/test.pdf.
server.js
app.get('/ePoint', (req,res)=>{
// some dumb code :P
});
demo.ts
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Headers } from '#angular/http';
import {Observable} from 'rxjs';
fileDownload() {
const headers = new HttpHeaders();
headers.append('Accept', 'application/pdf');
this._http.get('http://localhost:3000/ePoint', { headers: headers })
.toPromise()
.then(response => this.saveItToClient(response));
}
private saveItToClient(response: any) {
const contentDispositionHeader: string = response.headers.get('Content-Disposition');
const parts: string[] = contentDispositionHeader.split(';');
const filename = parts[1].split('=')[1];
const blob = new Blob([response._body], { type: 'application/pdf' });
saveAs(blob, filename);
}
i dont know where i did mistake. in browser network console. its shows 200 ok. but in normal browser console shows as below attachment
Note: i referred for ts file from here
helps much appreciated
try this...
component.ts
downloadDocument(documentId: string) {
this.downloadDocumentSubscription = this.getService.downloadScannedDocument(documentId).subscribe(
data => {
this.createImageFromBlob(data);
},
error => {
console.log("no image found");
$("#errorModal").modal('show'); //show download err modal
});
}
createImageFromBlob(image: Blob) {
console.log("mylog", image);
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(image, "download." + (image.type.substr(image.type.lastIndexOf('/') + 1)));
else {
var url = window.URL.createObjectURL(image);
window.open(url);
}
}
service.ts
downloadScannedDocument(documentId: string): Observable<any> {
let params = new HttpParams();
if (documentTypeParam == false)
params = params.set('onlyActive', 'false');
let fileResult: Observable<any> = this.http.get(`${this.apiBaseUrl}/${documentId}`, { responseType: "blob", params: params });
return fileResult;
}

Post operation not working with Angular 4

I'm learning Node.JS with Angular 4. I build a sample Node API for simple GET/POST request. My GET operation works fine and I am able to fetch data in Angular. My OST operation isn't getting called at all from Angular. If I use Postman, I'm able to call POST successfully and data also gets inserted in database.
Here is my sample code for Node POST:
app.post('/groups', function (req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
console.log('Request received with body' + req.body);
//DEV AWS MySQL
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'xxxxxxx',
user : 'xxxxxxx',
password : 'xxxxxxx',
database : 'xxxxxxx',
port : 3306
});
connection.connect();
connection.query('CALL storedprocedure(?, ?, ?, ?, ?, ?)', [req.body.group_avatar_image,req.body.name,req.body.display_name,req.body.unique_id,req.body.description,req.body.adzone], function (err, results, fields){
if (err)
res.send(results);
//res.status(201).send("Groups created successfully");
res.status(201).send(results[0]);
});
This works fine with Postman and I get 201.
Here is my Angular 4 code:
import { Injectable } from '#angular/core';
import { Http, Response,RequestOptions, Request, RequestMethod, Headers} from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import { Group } from './group';
#Injectable()
export class GroupsService{
private _GroupsUrl = 'http://localhost:5000/api/groups';
constructor(private _http: Http){};
getGroups(): Observable<Group[]> {
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
headers.append('Access-Control-Allow-Origin', '*');
//headers.append('Access-Control-Allow-Headers', "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding");
let options = new RequestOptions({ method: RequestMethod.Post, headers: headers, url:this._GroupsUrl });
//debugger;
return this._http.get(this._GroupsUrl)
.map((Response: Response) => <Group[]>Response.json()[0])
//.do(data => console.log ('ALL: ' + JSON.stringify(data)))
.catch(this.handleError);
}
CreateGroup(GroupM): Observable<string>{
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT, OPTIONS');
headers.append('Access-Control-Allow-Origin', 'http://localhost:4200');
headers.append('Access-Control-Allow-Headers', "X-Requested-With, Content-Type");
//let options = new RequestOptions({ method: RequestMethod.Post, headers: headers, body:JSON.stringify(GroupM), url:this._GroupsUrl });
let options = new RequestOptions({ method: RequestMethod.Post});
console.log('Calling ' + this._GroupsUrl + ' with body as :' + JSON.stringify(GroupM) + ' and request options are : ' + JSON.stringify(options));
var req = new Request(options.merge({
url: this._GroupsUrl
}));
debugger;
//return this._http.post(this._GroupsUrl,GroupM)
return this._http.post(req.url,JSON.stringify(GroupM),options)
.map(res => res.json())
.do(data => console.log ('ALL: ' + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error:Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server Error');
}
}
What is wrong here?
Finally able to resolve it using promise and it resolves the issue. Not sure what exactly is the issue with observable.
> CreateGroup(GroupObj:Group) : Promise<Group>{
return this._http
.post(this._GroupsUrl,JSON.stringify(GroupObj),{headers: this.headers})
.toPromise()
.then(res => res.json().data as Group)
.catch(this.handleError);
}
First of all, do yourself a favour and wrap Angular's Http service so that you don't have to manually add an auth token and headers for every request. Here's a simple implementation which you can build on:
First of all let's create a Cookies service which will act as a fallback where localStorage isn't supported:
#Injectable()
export class Cookies {
public static getItem(sKey) {
if (!sKey) {
return null;
}
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
}
public static setItem(sKey?, sValue?, vEnd?, sPath?, sDomain?, bSecure?) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
return false;
}
let sExpires = '';
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
}
public static removeItem(sKey, sPath?, sDomain?) {
if (!this.hasItem(sKey)) {
return false;
}
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
}
public static hasItem(sKey) {
if (!sKey) {
return false;
}
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
}
public static keys() {
let aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (let nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) {
aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]);
}
return aKeys;
}
}
Then a storage logger which keeps track of things added to the storage (useful for updating the auth token for every request when it changes):
import {Cookies} from '#services/cookies.service';
#Injectable()
export class StorageLogger {
private logger = new BehaviorSubject<any>(null);
public logger$ = this.logger.asObservable();
set(key: string, value: any): void {
try {
localStorage.setItem(key, JSON.stringify(value));
}
catch(err) {
Cookies.setItem(key, JSON.stringify(value));
}
this.get(key);
}
get(key: string) {
let item: any;
try {
item = JSON.parse(localStorage.getItem(key));
}
catch(err) {
item = JSON.parse(Cookies.getItem(key));
}
this.logger.next({value: item, key: key});
}
remove(keys: string[]) {
try {
for (const key of keys) {
localStorage.removeItem(key);
this.logger.next({value: null, key: key});
}
}
catch(err) {
for (const key of keys) {
Cookies.removeItem(key);
this.logger.next({value: null, key: key});
}
}
}
}
Then you want to wrap angular's Http:
#Injectable()
/* Wrapper for Angular's Http class, let's us provide headers and other things on every request */
export class HttpClient implements OnDestroy {
constructor(
private http: Http,
private storageLogger: StorageLogger
) {
this.getToken();
this.storageSubscription = this.storageLogger.logger$.subscribe(
(action: any) => {
if (action && action.key === tokenIdKey) {
this.getToken();
}
}
);
}
private storageSubscription: Subscription;
private token: string;
ngOnDestroy() {
this.storageSubscription.unsubscribe();
}
getToken(): void {
try {
this.token = localStorage.getItem(tokenIdKey);
}
catch(error) {
this.token = Cookies.getItem(tokenIdKey);
}
}
convertJSONtoParams(json: any): URLSearchParams {
const params: URLSearchParams = new URLSearchParams();
for (const key in json) {
if (json.hasOwnProperty(key) && json[key]) {
if (json[key].constructor === Array && !json[key].length) {
continue;
}
else {
params.set(key, json[key]);
}
}
}
return params;
}
getRequestOptions(params?: any): RequestOptions {
const headers = new Headers();
// headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Content-Type', 'application/json');
this.createAuthorizationHeader(headers);
return new RequestOptions({
headers: headers,
search: params ? this.convertJSONtoParams(params) : null
});
}
createAuthorizationHeader(headers: Headers): void {
headers.append('Authorization', this.token);
}
checkResponseStatus(err: any) {
if (err.status === 401) {
// If we want we can redirect to login here or something else
}
return Observable.of(err);
}
get(url: string, params?: any): Observable<Response> {
const options: RequestOptions = this.getRequestOptions(params);
return this.http.get(host + url, options).catch((err: Response) => this.checkResponseStatus(err));
}
post(url: string, data: any, params?: any): Observable<Response> {
const options: RequestOptions = this.getRequestOptions(params);
return this.http.post(host + url, data, options).catch((err: Response) => this.checkResponseStatus(err));
}
put(url: string, data: any, params?: any): Observable<Response> {
const options: RequestOptions = this.getRequestOptions(params);
return this.http.put(host + url, data, options).catch((err: Response) => this.checkResponseStatus(err));
}
delete(url: string, params?: any): Observable<Response> {
const options: RequestOptions = this.getRequestOptions(params);
return this.http.delete(host + url, options).catch((err: Response) => this.checkResponseStatus(err));
}
patch(url: string, data: any, params?: any): Observable<Response> {
const options: RequestOptions = this.getRequestOptions(params);
return this.http.patch(host + url, data, options).catch((err: Response) => this.checkResponseStatus(err));
}
head(url: string, params?: any): Observable<Response> {
const options: RequestOptions = this.getRequestOptions(params);
return this.http.head(host + url, options).catch((err) => this.checkResponseStatus(err));
}
options(url: string, params?: any): Observable<Response> {
const options: RequestOptions = this.getRequestOptions(params);
return this.http.options(host + url, options).catch((err: Response) => this.checkResponseStatus(err));
}
}
And finally you should also add a generic api service which you will call, instead of creating a new service for every part of your application. This will save you a lot of code and effort. Here it is:
import {IResponse} from '#interfaces/http/response.interface';
import {HttpClient} from '#services/http/http-client.service';
#Injectable()
export class AppApi {
constructor(private http: HttpClient) {}
get(url: string, params?: any): Observable<IResponse> {
return this.http.get(url, params)
.map((res: Response) => res.json() as IResponse)
.catch((error: any) => {
return Observable.throw(error.json().error || 'Server error');
}
);
}
post(url: string, data: any, params?: any) {
return this.http.post(url, data, params)
.map((res: Response) => res.json() as IResponse)
.catch((error: any) => {
return Observable.throw(error.json().error || 'Server error');
}
);
}
put(url: string, data: any, params?: any) {
return this.http.put(url, data, params)
.map((res: Response) => res.json() as IResponse)
.catch((error: any) => {
return Observable.throw(error.json().error || 'Server error');
}
);
}
delete(url: string, params?: any): Observable<IResponse> {
return this.http.delete(url, params)
.map((res: Response) => res.json() as IResponse)
.catch((error: any) => {
return Observable.throw(error.json().error || 'Server error');
}
);
}
}
You'll notice that I've also created an interface which types up my response from the backend, which is usually something like:
{error: any; data: any; results: number; total: number;}
Now that we've taken care of those problems, let's tackle your original question. The most likely reason as to why your request isn't running, is that you're not subscribing to the http observable. Observables are lazy so if you don't subscribe to it via .subscribe or #ngrx/effects, it just won't do anything.
So let's assume that you're calling CreateGroup like this:
this.groupsService.CreateGroup(data);
This won't do anything until you subscribe:
this.groupsService.CreateGroup(data).subscribe(() => {
// Here you can react to the post, close a modal, redirect or whatever you want.
});
I'd also recommend adding a .first() to your api calls as this will prevent you from having to unsubscribe from the observables manually when the component is destroyed.
So to use the implementation as above you'd simply do:
constructor(private appApi: AppApi) {}
...
this.appApi.post('/groups').first().subscribe(() => {
// Do something
});
I hope this is helpful.
Don't stringify the POST data in HTTP POST. Simply pass the object.

Resources