Reputation: 7240
I am new to angular and I am stuck in writing a post request to an external api: This is what i have tried:
import { Component } from '@angular/core';
import {HttpClientModule} from "@angular/common/http";
import {HttpParams} from "@angular/common/http";
import { OnInit } from '@angular/core';
@Component({
selector: 'mobile',
templateUrl: './mobile.component.html',
styleUrls: ['./../app.component.css']
})
export class MobileComponent implements OnInit {
constructor(private http: HttpClient){
ngOnInit(): void {
const postData = {mobile: 'MyNumber'};
this.http.post('MyAPI', postData, {
headers: new HttpHeaders().set('x-mobile-token', 'MyToken'),
}).subscribe();
}
}
}
But I get the following on a black overlay in my broswer:
Failed to compile.
./src/app/components/mobile.component.ts
Module parse failed: Unexpected token (24:18)
You may need an appropriate loader to handle this file type.
| void {
| const: postData = { mobile: 'MyNumber' },
| this: .http.post('MyAPI', postData, {
| headers: new HttpHeaders().set('x-mobile-token', 'MyToken'),
| }).subscribe(console.log('We are here!'))
@ ./src/app/app.module.ts 13:25-65
@ ./src/main.ts
@ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts
What am i missing?
Upvotes: 0
Views: 108
Reputation: 222552
ngOnInit
should be placed outside the constructor,
constructor(private http: HttpClient){
}
ngOnInit(): void {
const postData = {mobile: 'MyNumber'};
this.http.post('MyAPI', postData, {
headers: new HttpHeaders().set('x-mobile-token', 'MyToken'),
}).subscribe();
}
also suggestion is to place the post request inside a service and subscribe inside the component.
EDIT
As David mentioned, you should import HttpClient
and not HttpClientModule
import { HttpClient, HttpHeaders} from "@angular/common/http";
constructor(private http: HttpClient){ }
Upvotes: 2
Reputation: 4900
yes to what Saj said, also you are using the wrong name in the constructor. You imported HttpClientModule but injected HttpClient.
You're also missing HttpHeaders and you imported HttpParams, which you never use. Should be:
import { HttpClient, HttpHeaders} from "@angular/common/http";
constructor(private http: HttpClient){ }
Upvotes: 3