ionic4 problem with data response from API - ionic4

i have problem with data response from api the data is empty
this code fil servicelogin
#Injectable({
providedIn: 'root'
})
export class LoginService {
constructor( private http:HttpClient) { }
login(body) {
const headers=new HttpHeaders;
headers.append('content-Type', 'application/json'),
headers.append('api_key', '7zttgA4kFVsD2V2n0beMpzdLQRiSAKxtVEpyeW9MaEFEND0g')
headers.append('Access-Control-Allow-Origin','*')
headers.append('Access-Control-Allow-Methods','GET,POST')
headers.append('Access-Control-Allow-Headers','X-Requested-With ')
return this.http.post('https://bell.s2c.io/api/v1/Login', body,
{ headers: headers }).pipe(res=>res)
}}
the code login.ts
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
private formlogin : FormGroup;
Device:any
ListDevices:any
constructor(private servicelogin:LoginService,private formBuilder: FormBuilder,private router : Router
)
{
this.formlogin = this.formBuilder.group({
username: ['', Validators.required],
password: ['',Validators.required],
});
}
logForm(){
this.servicelogin.login(this.formlogin.value).subscribe(data=>{
console.log(data)
})
}
ngOnInit() {
}
}
i test with console.log(data) to see the data response but the data is empty what is the problem ?

Related

Unable to get data when making httpClient.get in angular 5

I am trying to do a http.get using httpclient. However, and i am getting
ReferenceError: data is not defined
Inside my component class when subscribing to service method.
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
const httpOptions = {
headers: new HttpHeaders()
.set('Authorization', 'Bearer xxxxx')
.set('Content-Type', 'application/json')
};
#Injectable()
export class SetsService {
constructor(private http: HttpClient) { }
getSet() {
return this.http.get('http://localhost:1234/api/users', httpOptions);
}
}
my component
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Router } from '#angular/router';
import { SetsService } from '../services/sets.service';
import { Observable } from 'rxjs/Observable';
#Component({
selector: 'app-sets',
templateUrl: './sets.component.html',
styleUrls: ['./sets.component.scss']
})
export class SetsComponent implements OnInit {
id: string = "";
set: any = {};
constructor(private route: ActivatedRoute, private router: Router, private _setsService: SetsService) {
this.route.params.subscribe(res => this.id = res.id);
}
ngOnInit() {
this.getSets();
}
getSets(){
this._setsService.getSet().subscribe(
(data) => { this.set = data },
err => console.error(err),
() => { console.log('done loading set') }
);
}}
When i look at the network the API call is successful and returning data.
Inside the html I am simply trying to print the set object.

In angular 5 ,Post data sending by http

I am sending post data for login (mobile and password). but i did not get response. below i attached two file 1) sign-in.component.ts and 2) user.service.ts . when click on submit button than call OnSubmit function(sign-in.component.ts)
sign-in.component.ts
import { Component, OnInit } from '#angular/core';
import { UserService } from '../../shared/user.service';
import { HttpErrorResponse } from '#angular/common/http';
import { Router } from '#angular/router';
#Component({
selector: 'app-sign-in',
templateUrl: './sign-in.component.html',
styleUrls: ['./sign-in.component.css']
})
export class SignInComponent implements OnInit {
isLoginError : boolean = false;
constructor(private userService : UserService,private router : Router) { }
ngOnInit() {
}
OnSubmit(userName,password){
console.log(userName + password);
this.userService.userAuthentication(userName,password)
.subscribe((data : any)=>{
console.log(data);
//localStorage.setItem('userToken',data.access_token);
this.router.navigate(['/home']);
},
(err : HttpErrorResponse)=>{
console.log(HttpErrorResponse);
this.isLoginError = true;
});
}
}
user.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Response } from "#angular/http";
import { Observable } from 'rxjs';
//import { Http, Response, RequestOptions, Headers } from '#angular/http';
//import 'rxjs/add/operator/map';
import { User } from './user.model';
#Injectable()
export class UserService {
readonly rootUrl = 'http://192.168.0.112:3001/admin/login';
constructor(private http: HttpClient) { }
userAuthentication(userName, password) {
var data = "mobile=" + userName + "&password=" + password ;
console.log(data);
var reqHeader = new HttpHeaders({ 'Content-Type': 'application/json','No-Auth':'True' });
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
return this.http.post('http://192.168.0.112:3001/admin/login',data,httpOptions);
}
}

The requested path contains undefined segment at index 0

authentication.service.ts in that my login service is define like this
import { Injectable } from '#angular/core';
import { Http, Headers, Response, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/Rx';
import 'rxjs/add/operator/map'
import { AuthHttp } from 'angular2-jwt';
import { Router } from '#angular/router';
#Injectable()
export class AuthenticationService {
token: string;
redirectUrl: any;
constructor(public router: Router, private http: Http, private authHttp: AuthHttp) {
//set token if saved in local storage
if (localStorage.getItem('authToken') != null) {
try {
// var currentUser =
JSON.parse(localStorage.getItem('currentUser'));
this.token = localStorage.getItem('authToken');
// this.token = currentUser && currentUser.token;
} catch (e) {
localStorage.removeItem("authToken");
}
}
}
login(username: string, password: string) {
return this.http.post('http://localhost:3002/api/authenticate',({ username: username, password: password }))
.map(res => {
console.log(res);
var authToken = res.json().token;
localStorage.setItem('authToken', authToken);
let redirectUrlTemp: any;
redirectUrlTemp = this.redirectUrl;
this.redirectUrl = null;
if (!redirectUrlTemp) {
console.log(redirectUrlTemp);
redirectUrlTemp = ['/login'];
}
this.router.navigate(redirectUrlTemp);
},
err => {
//alert(error.text());
console.log(err.text());
});
}
logout(){
// clear token remove user from local storage to log user out
this.token = null;
localStorage.removeItem('authToken');
}
}
when i try to post data using postman it works properly but from angular 2 it not allowing to redirect from next page
Login.component.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { AuthenticationService } from "app/services";
import { LoginRequest } from "app/models/models";
import { AlertService } from 'app/services';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { Http, Response } from '#angular/http';
#Component({
moduleId: module.id,
selector: 'login',
templateUrl: 'login.component.html'
})
export class LoginComponent implements OnInit {
model: any = {};
getLogin: LoginRequest[] = [];
loading = false;
error = '';
returnUrl: string;
constructor(
private route: ActivatedRoute,
private router: Router,
private http: Http,
private alertService: AlertService,
private authenticationService: AuthenticationService) { }
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password).subscribe(data => {
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
//let redirect = this.authenticationService.redirectUrl ? this.authenticationService.redirectUrl : '/allTask';
}
}
auth.guadr.ts
import { Injectable } from '#angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
import { AuthenticationService } from "app/services";
#Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthenticationService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (localStorage.getItem('authToken')) {
// logged in so return true
return true;
}
this.authService.redirectUrl =[state.url];
this.router.navigate(['/login']);
return false;
}
}
This error means that navigate array parameter with index 0 is undefined.
In your case you didn't set this.returnUrl in Login.component.ts
this.router.navigate([this.returnUrl]);

Creating restricted members area in Angular Fire 2

I am trying to make an application using angularfire 2. Can't find the perfect way to make the members area restricted that means only authenticated members can access that area. Here is my 'login.component.ts' file
import { Component, OnInit, HostBinding } from '#angular/core';
import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent {
state: string = '';
error: any;
login: FormGroup;
constructor(
public af: AngularFire,
private router: Router
) {
//official angfire 2 app example
//this.af.auth.subscribe(auth => console.log(auth));
}
ngOnInit() {
this.login = new FormGroup({
username: new FormControl('', Validators.required),
password: new FormControl('', Validators.required)
});
}
onSubmit() {
//console.log(this.login.value, this.login.valid);
var value = this.login.value;
//console.log(value.username);
//console.log(value.password);
this.af.auth.login({
email: value.username,
password: value.password,
},
{
provider: AuthProviders.Password,
method: AuthMethods.Password,
}).then(
(success) => {
console.log(success);
this.router.navigate(['/members']);
}).catch(
(err) => {
console.log(err);
this.error = err;
})
}
}
and the members.component.ts file
import { Component, OnInit } from '#angular/core';
import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2';
import { Router } from '#angular/router';
#Component({
selector: 'app-other',
templateUrl: './members.component.html',
styleUrls: ['./members.component.css']
})
export class MembersComponent implements OnInit {
//name: "";
//state: string = '';
constructor(
public af: AngularFire,
private router: Router
) {
this.af.auth.subscribe(auth => {
if(auth) {
console.log(auth);
}
});
}
logout() {
this.af.auth.logout();
console.log('logged out');
this.router.navigate(['/login']);
}
ngOnInit() {
}
}
I know my code may be seem like a dumb one but actually I am trying to study over this. But there is not enough documentation to solve my problem I guess. Thanks in advance.
https://coursetro.com/posts/code/32/Create-a-Full-Angular-Authentication-System-with-Firebase
this is a great tutorial that solves your problem

Angular 2 – No data afte api call

I am playing around with angular 2 and the heroes tutorial. The Problem is that I always get an empty object no matter which api I call.
Here is the code:
app.compomnent.ts
import { Component, OnInit } from '#angular/core';
import { Http, Response } from '#angular/http';
// Add the RxJS Observable operators we need in this app.
import './rxjs-operators';
#Component({
selector: 'my-app',
template: `
<h1>Test</h1>
`
})
export class AppComponent implements OnInit {
constructor(private http: Http) {}
private error: any;
ngOnInit() {
var request = this.http.get('http://date.jsontest.com');
console.log("Request: " + request);
console.log("Map: " + request.map(res => res));
console.log("Complete: " + this.http.get('http://date.jsontest.com')
.map(res => res.json())
.catch(this.error));
}
}
main.ts:
// The usual bootstrapping imports
import { bootstrap } from '#angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '#angular/http';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [
HTTP_PROVIDERS
]);
The result in my console:
An Observable doesn't do anything until you subscribe to it because they are lazy
ngOnInit() {
this.http.get('http://date.jsontest.com')
.map(res => res.json())
.subscribe(
data => this.data = data,
() => console.log('done'),
err => this.error(err));
}