Can't Get Response From Http in Angular - javascript

i need help in getting a response from http during ngOnInit(). I put an alert("hello") and it's not alerting anything. Is there something wrong in my code?
import { Component, OnInit } from '#angular/core';
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import 'rxjs/Rx';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
#Injectable()
export class DashboardComponent implements OnInit {
constructor(private http: Http) { }
ngOnInit() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let authToken = localStorage.getItem('auth_token');
headers.append('Authorization', `Bearer ${authToken}`);
return this.http
.get('http://sampeleposts', { headers })
.map(
response => {
console.log(response);
alert("hello");
},
error => {
alert(error.text());
console.log(error.text());
}
);
}
}

Looks like you are missing .subscribe()
return this.http
.get('http://sampeleposts', { headers })
.subscribe(
response => {
console.log(response);
alert("hello");
},
error => {
alert(error.text());
console.log(error.text());
}
);
That is how observables works. If you won't subscribe it won't executed
UPDATE:
Here is "how to http" taking from How to make post request from angular to node server:
import { Component } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user = { id : 1, name : 'Hello'};
constructor(private http: HttpClient) { }
callServer() {
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
this.http.post('http://127.0.0.1:3000/ping', JSON.stringify(this.user), {
headers: headers
})
.subscribe(data => {
console.log(data);
});
}
}
The example above is using the new '#angular/common/http' shipped in
Angular 4.3+ so as you mentioned in comments you are already using
one of these versions so I would recommend to switch to HttpClient
then.

Related

Get user data with Angular httpClient

I want to fetch user data, but I always get null. Here's my route:
router.get('/user', (req,res)=>{
res.send(req.user);
})
Don't want to go into the details, but on http://localhost:4000/auth/user, I have my user data, when I am logged in.
Here's my web service("framework" to all services) get part :
constructor(private http:HttpClient) { }
get(uri:string) {
return this.http.get(`${this.devUri}/${uri}`)
}
and AuthService(whole, because it's short):
import { Injectable } from '#angular/core';
import { WebService } from './web.service';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private webService: WebService) { }
getUser(){
return this.webService.get('auth/user');
}
}
And component with this data:
import { Component, OnInit } from '#angular/core';
import { AuthService } from 'src/app/services/auth.service';
#Component({
selector: 'app-public',
templateUrl: './public.component.html',
styleUrls: ['./public.component.css']
})
export class PublicComponent implements OnInit {
user: any;
constructor(private authService: AuthService) { }
ngOnInit(): void {
this.authService.getUser().subscribe( user => {
this.user = user;
console.log(user);
})
}
}
I am sure, that there is no problem with addresses or typos, but I suspect, that the problem is connected with asynchronism, but I don't know how to fix it.
I think it's server side code issue try changing that as followed.
router.get('/user', (req,res)=>{
res.status(200).json({
result: true,
user: 'Test result'
});
});
And in you component while onInit method add as followed
import { Component, OnInit } from '#angular/core';
import { AuthService } from 'src/app/services/auth.service';
#Component({
selector: 'app-public',
templateUrl: './public.component.html',
styleUrls: ['./public.component.css']
})
export class PublicComponent implements OnInit {
user: any;
constructor(private authService: AuthService) { }
ngOnInit(): void {
this.authService.getUser().subscribe( result => {
let temp:any = result;
this.user = temp.user;
console.log(this.user);
})
}
}
Hopefully this should work. Happy Coding!
Found the solution:
In server.js
app.use(
cors({
origin: "http://localhost:4200",
credentials: true
})
);
In webService.ts:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
withCredentials: true
}
get(uri:string) {
return this.http.get(`${this.devUri}/${uri}`, httpOptions)
}
and it's working now.

res.json() does not exist [duplicate]

This question already has answers here:
res.json() is a not a function in HttpClient Angular 2
(2 answers)
Closed 4 years ago.
I am trying to create a simple post in a service class using Angular/Typescript
My IDE does not give me any error, but when I call the function, I am getting undefined. I am not sure where the problem is based. I did some research, and it seems like the problem might be with the HttpClient I am importing, but I can not find anything relevant.
Front-end Function:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders} from '#angular/common/http';
import { Response } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class ServiceClassAuth {
auth: any;
user: any;
constructor(private http: HttpClient) {}
signinUser(user) {}
login(user) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
const loginUrl = 'http://localhost:3000/login';
return this.http.post(loginUrl, user, {
headers: headers
}).map((res: Response) => res.json());
}
}
A component which calls the Service:
import { Component, OnInit } from '#angular/core';
import {
MatDialog,
MatDialogRef,
MAT_DIALOG_DATA
} from '#angular/material';
import { Inject } from '#angular/core';
import { ServiceClassAuth } from '../service/service-class-auth';
#Component({
selector: 'app-signin',
templateUrl: './signin.component.html',
styleUrls: ['./signin.component.css'],
providers: [ServiceClassAuth]
})
export class SigninComponent implements OnInit {
username: String;
password: String;
ngOnInit() {}
constructor(
public dialogRef: MatDialogRef < SigninComponent > ,
#Inject(MAT_DIALOG_DATA) public data: any,
private authService: ServiceClassAuth) {}
onNoClick(): void {
this.dialogRef.close();
}
loginSubmit(postValues): void {
const user = {
'usr': postValues.value.usrname,
'psw': postValues.value.psw
}
const res = this.authService.login(user).subscribe(res => {
if (res.success) {
} else {
//DO ALERT
}
});
}
}
With HttpClient (Angular 4.3+), you do not have to use res.json() , the response object is JSON by default, Just use response directly.
return this.http.post(loginUrl, user, {
headers: headers
}).map((res: Response) => res);

angular 5 behaviorsubject not working with http [duplicate]

This question already has answers here:
Angular 2 Shared Data Service is not working
(3 answers)
Closed 4 years ago.
I am trying to get user type from the server and based on the role of the user display data. The http servise is running file and returning the desired data. I have two components. Login and Home components. After login a boolean variable is set to decide if the user is Admin or User. The login function is showing isAdmin variable true. But home component is showing it as false. I am using behaviorsubject and observable to sync the data.
Service
import { Injectable } from '#angular/core';
import {Http, Response} from "#angular/http";
import {Observable} from "rxjs/Observable";
import "rxjs/Rx";
import {IPosts} from "./posts";
import {IUser} from "./user";
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class ExamService {
public isAdmin = new BehaviorSubject<boolean>(false);
cast = this.isAdmin.asObservable();
private _postsURL = "http://localhost:3292/examservice.svc/ExamQs";
private _userURL = "http://localhost:3292/examservice.svc/GetUser";
constructor(private http: Http) {
}
getPosts(): Observable<IPosts[]> {
return this.http
.get(this._postsURL)
.map((response: Response) => {
return <IPosts[]>response.json();
})
.catch(this.handleError);
}
getUser(user:string,pass:string): Observable<IUser[]> {
return this.http
.get(this._userURL+"/"+user+"/"+pass)
.map((response: Response) => {
return <IUser[]>response.json();
})
.catch(this.handleError);
}
checkAdmin(data){
this.isAdmin.next(data);
}
private handleError(error: Response) {
return Observable.throw(error.statusText);
}
}
Login Component
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { ExamService } from "../exam.service";
import {IPosts} from "../posts";
import {IUser} from "../user";
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [ ExamService ]
})
export class LoginComponent implements OnInit {
_postsArray: IPosts[];
_userArray: IUser[];
ifuser: boolean = false;
Name: string;
Pass: string;
validated: boolean = true;
constructor(private apiSerivce: ExamService,private router:Router) { }
getPosts(): void {
this.apiSerivce.getUser(this.Name,this.Pass)
.subscribe(
resultArray => {
this._userArray = resultArray;
if(this._userArray[0].Role == "Admin")
{
this.ifuser = true;
this.apiSerivce.checkAdmin(this.ifuser);
}
else
{
this.apiSerivce.checkAdmin(this.ifuser);
this.router.navigate(['']);
}
},
error => console.log("Error :: " + error)
)
console.log(this.ifuser);
this.router.navigate(['']);
}
ngOnInit(): void {
this.apiSerivce.cast.subscribe(data =>
{
this.validated = data;
console.log("Login " + this.validated);
});
}
}
Home Component
import { Component, OnInit } from '#angular/core';
import { ExamService } from "../exam.service";
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [ ExamService ]
})
export class HomeComponent implements OnInit {
validated: boolean;
constructor(private apiSerivce: ExamService) { }
ngOnInit() {
this.apiSerivce.cast.subscribe(data =>
{
this.validated = data;
console.log("Home " + this.validated);
});
}
}
I have found the solution to this problem. Do not add service as provider in the child components instead add provider in app.component.ts file which is a parent component. so instead of
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [ ExamService ]
})
it should be like this in child components
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})
and in app.component.ts file it should be like this
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [ ExamService ]
})

Angular 5 component expecting an argument

Im trying a simple profile app, and all the sudden Im getting error TS2554
ERROR in /app/components/profile/profile.component.ts(25,3): error TS2554: Expected 1 arguments, but got 0.
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../../services/auth.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '#angular/router';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: Object;
constructor(
private auth: AuthService,
private flashMsg: FlashMessagesService,
private router: Router
) {
}
ngOnInit() {
this.auth.getProfile().subscribe( profile => {
this.user = profile.user;
},
err => {
return false;
});
}
}
auth.service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
import { tokenNotExpired } from 'angular2-jwt';
#Injectable()
export class AuthService {
authToken: any;
user: any;
constructor(
private http: Http
) {
}
getProfile(user) {
let headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type','application/json');
return this.http.get('http://localhost:3000/users/profile', {headers:headers})
.map(res => res.json());
}
loadToken() {
const token = localStorage.getItem('id_token');
this.authToken = token;
}
}
Your getProfile is expecting an argument named user but you are not passing it from the component
You need to pass an argument as follows,
this.auth.getProfile(user).subscribe( profile => {
this.user = profile.user;
},
err => {
return false;
});
or if you don't need an argument , remove it from your service method.

Can't resolve data from http.get() with Angular 2.0.0

I need to preload data on some url, so
I've resolver:
import {Injectable} from '#angular/core';
import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, } from '#angular/router';
import {Observable} from 'rxjs/Rx';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class ProfileResolver implements Resolve<any> {
constructor(
private _http: Http
) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<any>|any {
return this._http.get('/session').map(data => {
console.log(data);
return data;
});
}
}
and component:
import {Component} from '#angular/core';
import {RouterModule, ActivatedRoute} from '#angular/router';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
#Component({
selector: '[profile]',
host: {
class: 'profile-page app'
},
template: require('./profile.html')
})
export class Profile {
constructor(
private route:ActivatedRoute
) {
this.route.data.subscribe(data => {
console.log(data);
});
}
profile;
}
Route config:
{
path: 'profile',
loadChildren: () => System.import('../profile/profile.module'),
resolve: {
profile: ProfileResolver
},
},
Console.log in resolver shows received data, but in component it's empty object, whats wrong? When I used this code in rc4, all was fine.
Also if I change return _http.get(...) to simple value, like return "123"; this code will work. Thanks in advance.
Fetching your data can (and should) be done via
this.profile = this.route.snapshot.data['profile'];
Entire and complete explanation can be found here:
http://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html

Categories

Resources