Angular2 Router navigate is not working in service [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
Now I am trying to use Angular2 Router.navigate, but it isn't working.
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import { Router } from '#angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
#Injectable()
export class HttpService {
constructor(
public _http: Http,
public _router: Router
)
{
}
public sendPostRequestWithParams(url, params) {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(url, params, {headers: headers})
.map(res => res.json())
.catch(this.handleServerError);
}
public handleServerError(error: Response) {
let jError = error.json() && error.json()['error'];
if (jError == 'Unauthenticated.') {
alert("You are not unauthenticated. Please login correctly!");
this._router.navigate(['login']);
return Observable.throw("You are not unauthenticated. Please login correctly!");
}
return Observable.throw(error.json() || 'Server error'); // Observable.throw() is undefined at runtime using Webpack
}
}
But when calling handleServerError, it shows error "Cannot read property navigate of undefined".
Is it impossible to use Router in Service?

Change below line
this._router.navigate(['login']); => this._router.navigate(['/login']);

Related

Angular 7 - [object Object] receiving as the output

I have node backend with couple of endpoints related to stripe payment gateway. When I use POSTMAN to check the api call it works fine and give result. But I could not call it in angular service.ts and component.ts files. Please advice on this.
stripe.js - backend
router.get("/public-key", (req, res) => {
res.send({
publicKey: "pk_test_123",
});
});
stripe-script.service.ts
import { Injectable } from '#angular/core';
import { ScriptLoadingService } from './script-loading.service';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class StripeScriptService {
private baseUrl = 'https://js.stripe.com/v3/';
private globalVar = 'stripe';
private sessionId;
constructor(private scriptLoadingService: ScriptLoadingService, private http: HttpClient) { }
getPublicKey() {
return this.http.get('http://localhost:3000/api/stripe/public-key');
}
}
stripe.component.ts
testStripe(): void {
this.stripeScriptService.getPublicKey();
}
I receive the api call output as follows.

subscribing in Angular

I am completely new to Angular and I've created a project using SpringBoot 2.0.5.RELEASE, Angular 5 and spring data to build an end to end single page java web application. I use spring boot 1.5 to expose REST APIs and angular5 with routing to build the client that will consume the APIs exposed by the server.
I've defined this component:
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { User } from '../models/user.model';
import { UserService } from './user.service';
#Component({
templateUrl: './add-user.component.html'
})
export class AddUserComponent {
user: User = new User();
constructor(private router: Router, private userService: UserService) {
}
createUser(): void {
alert ('lala');
this.userService.createUser(this.user)
.subscribe( data => {
alert('User created successfully.');
});
}
}
in the page I can see the alert lala, but not 'User created successfully.' but I have no idea why
The link address when I create a user is this is this one http://localhost:4200/api/users
This is my proxy.config.json file:
{
"/api/*": {
"target": "http://localhost:8080/user-portal",
"secure": false
}
}
and from curl is fine :
curl -X POST -H "Content-Type: application/json" "http://localhost:8080/user-portal/api/users"
and user.service.ts:
import {Injectable} from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { User } from '../models/user.model';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
#Injectable()
export class UserService {
constructor(private http: HttpClient) {}
private userUrl = '/api/users';
public getUsers() {
return this.http.get<User[]>(this.userUrl);
}
public deleteUser(user) {
return this.http.delete(this.userUrl + '/'+ user.id);
}
public createUser(user) {
return this.http.post<User>(this.userUrl, user);
}
}
Firstly, best not to use alert. Use console.log. Secondly, you are only handling success, you are not handling failure. Do this:
createUser(): void {
console.log('lala');
this.userService.createUser(this.user)
.subscribe(data => {
console.log('User created successfully', data);
},
err => {
console.log('There was an error', err);
},
() => {
console.log('I have completed now and nothing will ever be emitted from this Observable again');
});
}
The error handler will be executed if the HTTP response is not a success response, viz if the status code of the response is not in the 2xx range.
Check your browser network tab also to see if the HTTP request is failing.
You prob also want to debug this:
public createUser(user) {
console.log('userUrl', this.userUrl)
console.log('user', user)
return this.http.post<User>(this.userUrl, user);
}
To make sure all is as expected.
In Chrome hit F12 to open the dev tools and go to the network tab. Make sure that a request is being made to the end point and that it is not throwing and error.

Angular/TypeScript : How to resolve this compilation issue?

Hell
I ma new in angular 5. I am create a login and auth service. But i cannot compile my code. Here is my code
// user.service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
#Injectable()
export class UserService {
private loggedIn = false;
constructor(private http: Http) {
// this.loggedIn = !!localStorage.getItem('auth_token');
}
//authenticate user with dummy logic because i use a json-server
authenticate(login:string, password:string) {
console.log('Authenticate ....');
const credentials = {login:login, password:password};
let headers = new Headers();
headers.append('Content-Type', 'application/json');
var result = this.http
.get(
'/users?login?'+JSON.stringify(login),
{ headers }
);
if(result.password==password){
return true;
}
return false;
}
}
When i compile ( ng server ) i get the following error
ERROR in src/app/auth/user.services.ts(28,17): error TS2339:
Property 'password' does not exist on type 'Observable<Response>'.
Line 28 is : if(result.password==password){
I don't know what i am missing ?I try to understand the Observable concept. If you add an idea, it will help me.
Thanks
result here is an observable, you need to subscribe to it to get response.
Something like below:
var result = this.http.get(
'/users?login?'+JSON.stringify(login),
{ headers }
);
//result is an observer here, you have to subscribe to it
result.subscribe((response) => {
if(response.password==password){
return true;
}
return false;
});
You can check this awesome article: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
Use Observables properly
Use HttpClient, not old Http
You can also define a User class to make typing more strict.
// user.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
#Injectable()
export class UserService {
private loggedIn = false;
constructor(private http: HttpClient) {
// this.loggedIn = !!localStorage.getItem('auth_token');
}
//authenticate user with dummy logic because i use a json-server
authenticate(login:string, password:string) :Observable<boolean> {
return this.http
.get('url/whatever') //returns a User object having password
.map(user => user.password === password); // maps result to the desired true or false value
}
}
// to consume the service from a component, for example
this.userService.authenticate('myusername', 'mypassword')
.subscribe(authenticated => {
console.log('login status', authenticated)
})
You are trying to access the observable returned from the http call.
To get the information in the observable you have to subscribe to it.
For detailed information about hot to get remote data please read this:
https://angular.io/guide/http
NOTE: You should not use the deprecated angular/http. Use angular/common/http instead.

Angular 5: read local json file

I use Angular 5 for my project, i need to get the data from a local json file, i created a service ""JsonDataService" and i put the file in "assets/data" folder, but i can not get the file, igot always the error: Error: [object Object] at viewWrappedDebugError....
Here is the code:
import {Injectable} from '#angular/core';
import {HttpClient, HttpHeaders} from '#angular/common/http';
import {Observable} from 'rxjs/Observable';
#Injectable()
export class JsonDataService {
constructor(private httpClient: HttpClient) {
}
public getDepartmentData(): Observable<any> {
console.log('getDepartmentData');
const apiUrl = './assets/data/french-regions-departments.json';
return this.httpClient.get(apiUrl);
// .map((res: any) => {
// const data = res.json();
// return data;
// });
}
}
And the call is here:
jsonDataService.getDepartmentData().subscribe(data => console.log(data));
I found some posts about the subject, but none of them works for me.
I can see the content of the json file from the chrome with the url: localhost:4200/assets/data/french-regions-departments.json
Do you have any solution, please?
The api url should only be
const apiUrl = 'assets/data/french-regions-departments.json';

Alert + Angular

I have an angled application where I am trying to perform an insert methods on a backend. I need that after the response of the backend display an alert like for example the one of SweetAlert. But I do not know any components that do this. SweetAlert works at the click of a button, not the response of a backend.
For exemple:
My real question is:
How do I enable SweetAlert in typescript
Can anybody help me?
Make a http request and subscribe it in you desired component and on success of http request, as you get response- show alert.
service.ts
import { Injectable } from '#angular/core';
import { HttpClient, Response, RequestOptions, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
export class CcDataServiceService {
constructor(private http: HttpClient) { <-- httpclient for angular6
}
getData(): Observable<any[]> {
return this.http.get('https://')
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
const body = res.json();
return body || [];
}
private handleError(error: any) {
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
console.log('Server Error!');
return Observable.throw(errMsg);
}
}
component.ts
import swal from 'sweetalert'
constructor(public jsonDataService: CcDataServiceService) {
}
ngOnInit() {
let thisx = this;
this.jsonDataService.getData().subscribe(
function (success) {
// alert here on success
swal("Hello world!");
},
error => console.log('Getting Server Data Error :: ' +
JSON.stringify(error)));
}
Link:- https://stackblitz.com/edit/angular6-7scyt7?file=app/app.component.ts

Categories