Angular 5: read local json file - javascript

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';

Related

How can I get the user's email from Keycloak in this Angular app?

I am working on an app in Angular 14 that requires authentication/authorization, reason for witch I use Keycloak Angular
.
I need to get the currently logged in user's data from the application.
For this purpose, I have a service:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { User } from '../../../models/user';
#Injectable({
providedIn: 'root'
})
export class UserFormService {
httpOptions: object = {
headers: new HttpHeaders({
'Content-Type' : 'application/json'
})
}
apiURL: string = 'http://localhost:8080';
constructor(private http: HttpClient) { }
public currentUserEmail: any;
public currentUserData: any;
public async getUserEmail(){
let currentUser = await this.keycloakService.loadUserProfile();
this.currentUserEmail = currentUser.email;
}
public getUserByEmail(email: string): Observable<User>{
return this.http.get<User>(`${this.apiURL}/getUserByEmail/${email}`, this.httpOptions);
}
}
I use it in a component:
public getUserByEmail() {
this.supplierFormService.getUserByEmail(this.currentUserEmail).subscribe(response => {
this.currentUser = response;
console.log('currentUser: ', response);
});
}
In keycloak.init.ts I have:
import { KeycloakService } from 'keycloak-angular';
export function initializeKeycloak(keycloak: KeycloakService) {
return () =>
keycloak.init({
config: {
url: 'http://localhost:8085',
realm: 'MyRealm',
clientId: 'my-app'
},
initOptions: {
onLoad: 'check-sso',
silentCheckSsoRedirectUri:
window.location.origin + '/assets/silent-check-sso.html'
}
});
}
ngOnInit(): void {
// Get user's email
this.getUserEmail();
// Get user's data by email
this.getUserByEmail();
}
The problem
Instad of returning the user's data, the service throws a 500 (Internal Server Error) and the email is undefined, as can be seen below:
http://localhost:8080/getUserByEmail?email=undefined
How do I fix this problem?
You should sync those two calls, the getUserByEmail may be excecuted faster then currentUserEmail is set:
async ngOnInit(): void {
// Get user's email
await this.getUserEmail();
// Get user's data by email
this.getUserByEmail();
}
decode jwt token returned from keycloak. It contains current user data and Id
Then get user by this id

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.

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.

Angular2 Router navigate is not working in service [duplicate]

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']);

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