Login In Angular 10 with JWT - javascript

I am facing trouble in logging in with JWT in angular, I have successfully logged in via the login and also stored the token, but my frontend is not updating itself with the same
Auth.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { ErrorprocessorService } from './errorprocessor.service';
import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';
interface LogUser {
success: boolean;
message: string;
token: string;
user: {
name: string;
username: string;
email: string;
};
}
interface JWTResponse {
success: boolean;
message: string;
user: any;
}
#Injectable({
providedIn: 'root'
})
export class AuthService {
tokenKey = 'JWT';
isAuthenticated: Boolean = false;
username: Subject<string> = new Subject<string>();
authToken: string = undefined;
constructor(private http: HttpClient, private errorProcessor: ErrorprocessorService) { }
loadUserCredentials() {
const credentials = JSON.parse(localStorage.getItem(this.tokenKey));
console.log('Loading User Credentials : ', credentials);
if (credentials && credentials.username !== undefined) {
this.useCredentials(credentials);
if (this.authToken) {
this.checkJWTtoken();
}
}
}
checkJWTtoken() {
this.http.get<JWTResponse>('http://localhost:3000/auth/checkToken')
.subscribe(res => {
console.log('JWT Token Valid: ', res);
this.sendUsername(res.user.username);
}, err => {
console.log('JWT Token Invalid: ', err);
this.destroyUserCedentials();
});
}
storeUserCredentials(credentials: any) {
console.log('Storing User Credentials : ', credentials);
localStorage.setItem(this.tokenKey, JSON.stringify(credentials));
this.storeUserCredentials(credentials);
}
useCredentials(credentials: any) {
this.isAuthenticated = true;
this.sendUsername(credentials.username);
this.authToken = credentials.token;
}
sendUsername(name: string) {
this.username.next(name);
}
loginUser(user: any): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post<LogUser>('http://localhost:3000/auth/login', user, httpOptions)
.pipe(map(res => {
this.storeUserCredentials({ username: user.username, token: res.token });
return { 'success': true, 'username': user.username };
}))
}
destroyUserCedentials() {
this.authToken = undefined;
this.clearUsername();
this.isAuthenticated = false;
localStorage.removeItem(this.tokenKey);
}
clearUsername() {
this.username.next(undefined);
}
logOut() {
this.destroyUserCedentials();
}
isLoggedIn(): Boolean {
return this.isAuthenticated;
}
getUsername(): Observable<string> {
return this.username.asObservable();
}
getToken(): string {
return this.authToken;
}
}
Login.component.ts
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
errMsg: string;
user = {
username: '',
password: ''
};
constructor(private authService: AuthService, private router: Router) { }
ngOnInit(): void {
}
onSubmit(): void {
console.log(this.user);
this.authService.loginUser(this.user)
.subscribe(res => {
if (res.success) {
this.router.navigate(['/dashboard']);
} else {
console.log(res);
}
}, err => {
this.errMsg = <any>err;
});
}
}
Auth-guard.server.ts
import { Injectable } from '#angular/core';
import { Router, CanActivate } from '#angular/router';
import { AuthService } from './auth.service';
#Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) { }
canActivate(): boolean {
if (!this.auth.isLoggedIn()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
Header.component.ts
import { Component, OnInit, OnDestroy } from '#angular/core';
import { Subscription } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
username: string = undefined;
subscription: Subscription;
constructor(private authService: AuthService, private router: Router) { }
ngOnInit(): void {
this.authService.loadUserCredentials();
this.subscription = this.authService.getUsername()
.subscribe(name => { console.log(name); this.username = name; });
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
openProfile(): void {
this.router.navigate(['/profile']);
}
logOut(): void {
this.username = undefined;
this.authService.logOut();
}
}
can anyone help me with this?
Thanks in advance and also if you need any other files ping me ill send you those

Your code has infinite loop:
storeUserCredentials(credentials: any) {
console.log('Storing User Credentials : ', credentials);
localStorage.setItem(this.tokenKey, JSON.stringify(credentials));
this.storeUserCredentials(credentials);
}
It could be be an error that blocking your app running

Related

Can't resolve all parameters for AuthService on Angular

I'm trying to start my angular app and i'm getting this error below for some reason. I tried removing the auth service provider from my component and removing also the auth service from my constractor inside my component, but nothing changed... I can't figure out what i'm doing wrong and i'm beginner on angular.
The error:
Can't resolve all parameters for AuthService: (?, ?, [object Object]).
My component:
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { AuthService } from '../../Services/auth.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [AuthService]
})
export class LoginComponent {
isUserLoggedIn: boolean;
emailAddress: string;
password: string;
invalidLogin: boolean;
invalidText: string;
constructor(private authService: AuthService, private router: Router) {
if (authService.getCurrentUser() != null) {
router.navigate(['/home']);
}
}
login() {
if (!this.authService.login(this.emailAddress.toString(), this.password.toString())) {
this.invalidLogin = true;
this.invalidText = "Wrong Email Address or password";
}
}
}
My service:
import { Inject } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
import { UserModel } from "../Models/UserModel";
export class AuthService {
constructor(private router: Router, private http: HttpClient, #Inject('BASE_URL') private baseUrl: string) {}
login(email: string, password: string) {
const headers = {'Content-Type': 'application/json', };
const body = { emailAddress: email, password: password };
let userLoggedIn: Boolean = false;
this.http.post<any>(this.baseUrl + "Api/Login", body, { headers }).subscribe(response => {
if (response.username != null) {
let user: UserModel
user = response;
this.router.navigate(['/home']);
this.saveUserToLocalStorage(user);
userLoggedIn = true
}
}, error => console.error(error));
return userLoggedIn;
}
saveUserToLocalStorage(loggedInUser: UserModel) {
sessionStorage.setItem("loggedInUser", JSON.stringify(loggedInUser));
}
getCurrentUser() {
return sessionStorage.getItem("loggedInUser")
}
logout() {
sessionStorage.removeItem("loggedInUser")
this.router.navigate([''])
}
createUser(userData: UserModel) {}
sendResetPasswordEmail() {}
}
I think this is because you use Router in your constructor, try to do this
constructor(private readonly injector: Injector,
...) {}
public get router(): Router {
return this.injector.get(Router);
}
I found what was the problem. I had to mark my service class as #Injectable()
Like this:
#Injectable()
export class SchoolService {
...
}

refresh header component after login using angular 11

actually i am using angular 11 and i want to show username in header component but my header is load first then my login component is load so after loading login component data store in local storage that why when i refresh page then user name is show but i dont want refresh page so what can i do for that please help me
below code is my authservice
import { Injectable } from '#angular/core';
import { environment } from 'src/environments/environment'
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
baseUrl = environment.apiUrl;
constructor(private http: HttpClient, private router: Router) { }
loginUser(data: {}) {
return this.http.post(this.baseUrl + 'signin', data)
}
isLoggedIn() {
//console.log(localStorage.getItem('user_details'))
if (localStorage.getItem('user_details') !== undefined && localStorage.getItem('user_details') !== null) {
//console.log("if")
return true;
} else {
return false;
}
//return !!localStorage.getItem('user_details')
}
getUserName(): any {
const userName = localStorage.getItem('user_details');
if (userName) {
return JSON.parse(userName);
}
return false;
}
isLoggedOut() {
localStorage.removeItem('user_details');
this.router.navigate(['/login']);
}
}
this is my header component
import { Component, OnInit, HostListener } from '#angular/core';
import { AuthService } from '../../login/services/auth.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
scrolled: boolean = false;
userName: string = '';
fname: string = '';
lname: string = "";
#HostListener("window:scroll", [])
onWindowScroll() {
this.scrolled = window.scrollY > 1;
}
constructor(public auth: AuthService, private router: Router) { }
ngOnInit(): void {
if (this.auth.isLoggedIn()) {
this.router.navigate(['dashboard']);
}
const user = this.auth.getUserName();
this.userName = user.role_name;
this.fname = user.first_name.charAt(0);
this.lname = user.last_name.charAt(0);
}
logOut() {
localStorage.removeItem('user_details');
this.router.navigate(['/login']);
}
}
below is login component
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
import { AuthService } from './services/auth.service';
import { Router } from '#angular/router';
import { Md5 } from 'md5-typescript';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm: any;
data: any;
success: any;
message: any;
constructor( private auth: AuthService, private router: Router ) {
this.loginForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.pattern('^[\\w-\\.]+#([\\w-]+\\.)+[\\w-]{2,4}$')]),
password: new FormControl('', Validators.required)
});
}
ngOnInit(): void { }
onSubmit() {
console.log(this.loginForm.value);
let data = {
"email_id": this.loginForm.value.email,
"password": Md5.init(this.loginForm.controls['password'].value)
}
this.auth.loginUser(data).subscribe(
(response: any) => {
this.data == response;
this.success == response.success;
if (response.success == 1) {
localStorage.setItem("user_details", JSON.stringify(JSON.parse(response.data).user_details))
console.log(localStorage.getItem('user_details'));
this.router.navigate(['dashboard']);
} else {
this.message = response.message;
}
}
);
this.loginForm.reset();
}
}
You can't use local storage to get logged in user details, because you component is already loaded. You need to create shared service using Subject or Behaviorsubject (RXJS operatoer) You can find example https://medium.com/#hitensharma1515/sharing-data-between-components-using-service-2d662a653a89

Angular9:core.js:6228 ERROR Error: Uncaught (in promise): Error: Can't resolve all parameters for Subscription: (?)

I'm a newbie and learning Angular.
I want to pass data between two components (not a parent-child component). I write a service.ts file to achieve it then met this error. I have found a lot in Stackoverflow, but seems no effects.
I don't know what went wrong, so I will put all the code out.
Below is the code.
By the way, how to solve "It looks like your post is mostly code; please add some more details."?
//service
import { Injectable } from '#angular/core';
import {Observable} from 'rxjs';
import { Subject } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class TransfermessageService {
public receiveMsg:any;
constructor() { }
public subject = new Subject<any>();
sendMessage(message: any) {
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
//component 1
import { Component, OnInit } from '#angular/core';
import {RequestService} from '../../../services/request/request.service';
import {Router,NavigationStart, GuardsCheckEnd,ResolveStart,NavigationError, Event as NavigationEvent } from '#angular/router';
import {TransfermessageService} from '../../../services/common/transfermessage/transfermessage.service';
#Component({
selector: 'app-login-session-code',
templateUrl: './login-session-code.component.html',
styleUrls: ['./login-session-code.component.scss'],
})
export class LoginSessionCodeComponent implements OnInit {
public riskRole: string = localStorage.getItem('userRole');
public sessioncode: any;
public token_user: any;
constructor(
public RS: RequestService,
public router: Router,
public TMS: TransfermessageService,
) {
}
ngOnInit(){
}
checkInputCall(){
const api = this.RS.baseURL+ '/login/checkInput';
const token_api= this.RS.baseURL+ '/login/checkToken';
const parameters:object = {
"email": localStorage.getItem('email'),
"input": this.sessioncode,
"type": localStorage.getItem('type')
}
this.RS.checkInput(api,parameters).subscribe(res => {
if(res['data'].input_check) {
localStorage.setItem('checkInput', JSON.stringify(res['data']));
this.RS.checkToken(token_api,{"token": res['data'].user.token}).subscribe(res => {
this.token_user = res;
this.TMS.sendMessage({"ss": "ssss"});
this.router.navigate(['/home']);
// console.log(res); //return token_user
})
}else {
alert("session code is not true");
}
})
}
ngAfterViewChecked(): void {
this.router.events.subscribe((event: NavigationEvent) => {
if(event instanceof NavigationStart) {
console.log(event);
}
});
this.router.events.subscribe((event: NavigationEvent) => {
if(event instanceof GuardsCheckEnd) {
console.log(event,'GuardsCheckEnd');
}
});
this.router.events.subscribe((event: NavigationEvent) => {
if(event instanceof NavigationError) {
console.log(event,'NavigationError');
}
});
}
}
//components 2
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import {TransfermessageService} from '../../services/common/transfermessage/transfermessage.service';
import {Subscription} from 'rxjs';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
providers: [TransfermessageService]
})
export class HomeComponent implements OnInit {
public ctrlHomeDetailTag: boolean = true;
public ctrlHomeBasicTag: boolean = true;
public ctrlTags: boolean = true;
public receiveMsg: any;
constructor(
public router: Router,
public TMS: TransfermessageService,
public Subscription: Subscription
) {
}
ngOnInit(): void {
console.log('home page');
const receiveMsg = this.TMS.getMessage();
console.log(receiveMsg,'parameters');
}
// ngAfterViewInit():void {
// this.Subscription = this.TMS.getMessage().subscribe(message => {
// this.receiveMsg = JSON.parse(message);
// console.log('this.receiveMsg', this.receiveMsg);
// })
//}
ngonChanges() {
}
ngDoCheck() {
}
ngOnDestroy(): void {
// this.Subscription.unsubscribe();
}
}

guard in angular how can I get value from auth.service.ts (user login or not)

I use canActivate in history.guard and how can I check if the user login or not!
the value which I console always return false!
Do I need to create a new function in auth.service or just edit in history.guard ? Is there any way instead of using subscribe ??
auth.service.ts
import { Injectable } from '#angular/core';
import { Router } from '#angular/router';
import { Subject } from 'rxjs/Subject';
import { ApiService, VERSION, ENDPOINT } from '../api/api.service';
import { Observable, BehaviorSubject } from 'rxjs';
#Injectable()
export class AuthService {
logger = new BehaviorSubject<Object>(false);
referralRoute: string;
constructor(
private router: Router,
private api: ApiService
) {
}
logout() {
localStorage.removeItem('access-token');
localStorage.removeItem('uid');
localStorage.removeItem('client');
this.redirectToLogin();
this.logger.next(false);
}
postLogin(body: any) {
this.api.get(['token.json'], {}).subscribe(
(res: any) => {
localStorage.setItem('access-token', res['access-token']);
localStorage.setItem('uid', res['uid']);
localStorage.setItem('client', res['client']);
this.logger.next(true);
this.redirectToPrevStep();
},
(err) => {
this.logger.next(err);
});
}
checkLogin(body: any) {
this.api.get([VERSION, ENDPOINT.checkLogin], {}).subscribe(
(res: any) => {
this.logger.next(true);
},
(err) => {
this.logger.next(err);
});
}
checkUserLogin() {
const isLogin = !!localStorage.getItem('JWT_TOKEN');
if (isLogin) {
this.logger.next(true);
} else {
this.logger.next(false);
}
}
subscribeLogger(): Observable<Object> {
return this.logger.asObservable();
}
isAuthenticated() {
const token = localStorage.getItem('access-token');
let isAuthenticated: boolean;
if (this.isTokenInvalid()) {
localStorage.removeItem('access-token');
isAuthenticated = false;
} else {
isAuthenticated = true;
}
return isAuthenticated;
}
getUserInfo() {
const token = localStorage.getItem('access-token');
// let userInfo = this.jwtHelper.decodeToken(token);
return {};
// this.jwtHelper.decodeToken(token),
// this.jwtHelper.getTokenExpirationDate(token),
// this.jwtHelper.isTokenExpired(token)
// );
}
isTokenInvalid() {
const token = localStorage.getItem('access-token');
if (!token) {
return true
} else {
// this.api.setHeaders(token);
return false;
}
}
/**
* Helper method for set up referral route, enable useful redirect after login
* #method setRoute
* #param {string} route Route as defined in app.routes, eg. /user/1
*/
setRoute(route: string): void {
this.referralRoute = route;
}
redirectToPrevStep() {
const route = this.referralRoute ? this.referralRoute : '/';
this.router.navigateByUrl(route);
}
redirectToLogin(current: string = '/') {
// Store current url as referral and use latter for login redirection
this.setRoute(current);
window.scroll(0, 0);
this.router.navigate(['/auth/login']);
}
}
history.guard.ts
import { Injectable } from '#angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
import { AuthService } from '../../core/service/auth/auth.service';
#Injectable({ providedIn: 'root' })
export class HistoryGuard implements CanActivate {
checkUserLogin: boolean;
constructor(
private router: Router,
private auth: AuthService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const checkUserLogin = this.auth.subscribeLogger().subscribe(
(data: any) => {
this.checkUserLogin = data;
}
);
if (!this.checkUserLogin) {
return this.router.navigate(['mypage']);
}
else {
return this.checkUserLogin;
}
}
}
history.module.ts
import { NgModule } from '#angular/core';
import { HistoryComponent } from './history.component';
import { HistoryItemComponent } from './history-item/history-item.component';
import { RouterModule, Routes } from '#angular/router';
import { CommonModule } from '#angular/common';
import { HistoryGuard } from './history.guard';
const routes: Routes = [
{
path: '',
component: HistoryComponent,
canActivate: [HistoryGuard]
},
{
path: ':id',
component: HistoryItemComponent,
canActivate: [HistoryGuard]
}
];
#NgModule({
imports: [
CommonModule,
RouterModule.forChild(routes)
],
declarations: [HistoryComponent, HistoryItemComponent]
})
export class HistoryModule { }
Hi this how I implemented AuthGuard, you can check just if in local storage is a JWT token or not, because on logout you should delete jwt token from localStorage and that's it
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.authService.isLoggedIn()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
// Auth service
isLoggedIn() {
return Boolean(this.getToken());
}
getToken() {
return this.localStorage$.retrieve('authenticationToken');
}
logout() {
this.localStorage$.clear('authenticationtoken');
}
This is how your canActivate should look like:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.auth.subscribeLogger().pipe(
tap(login => {
if(!login) {
this.router.navigate(['mypage']); // If user is not logged in, just navigate away
}
})
);
}

Angular: Can't return value

I have API for getting information about one specific restaurant in the database, but I have to get it with a POST request. I successfully get restaurantID from auth.service and another API when the restaurant is logged in, But when I tried to log restaurant in console, I get undefined. Uniformly I don't have permission to show API here. The code:
Informacije component:
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';
#Component({
selector: 'app-informacije',
templateUrl: './informacije.component.html',
styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
restaurant: Restaurant;
loggedRestaurant: LoggedRestaurant;
restaurantID = this.authService.currRestaurant[0].id;
constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }
getRestaurant() {
return this.restaurantService.getRestaurant(this.restaurantID).toPromise().then(data => {
this.loggedRestaurant = data;
});
}
async ngOnInit() {
await this.restaurantService.getRestaurant(this.restaurantID).subscribe(
data => {
this.loggedRestaurant = data;
console.log(this.loggedRestaurant)
})
this.restaurant = this.authService.currRestaurant[0];
console.log(this.restaurant)
console.log(this.loggedRestaurant)
console.log(this.restaurantService.restaurantID)
}
}
restaurant.service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { AuthService } from './auth.service'
#Injectable({
providedIn: 'root'
})
export class RestaurantService {
private restaurantUrl = 'xxxxxx';
public restaurant: Restaurant;
public loggedRestaurant: LoggedRestaurant
public restaurantID = this.authService.currRestaurant[0].id
constructor(private http: HttpClient, private authService: AuthService) { }
getRestaurant(ID): Observable<LoggedRestaurant> {
console.log('ID je razmak' + this.restaurantID);
return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
}
}
auth.service
import { Injectable } from '#angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '#angular/common/http';
import { throwError, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
#Injectable({
providedIn: 'root'
})
export class AuthService {
loginUrl = 'xxxxx';
errorData: {};
constructor(private http: HttpClient) { }
redirectUrl: string;
login(email: string, password: string) {
var postData = {email: email, password: password};
return this.http.post<Restaurant>(this.loginUrl, postData)
.pipe(map(restaurant => {
if (restaurant) {
localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
return restaurant;
}
}),
catchError(this.handleError)
);
}
isLoggedIn() {
if (localStorage.getItem('currentRestaurant')) {
return true;
}
return false;
}
getAuthorizationToken() {
const currentRestaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
return currentRestaurant.token;
}
logout() {
localStorage.removeItem('currentRestaurant');
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong.
console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
}
// return an observable with a user-facing error message
this.errorData = {
errorTitle: 'Oops! Request for document failed',
errorDesc: 'Something bad happened. Please try again later.'
};
return throwError(this.errorData);
}
currRestaurant: Restaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
currID = this. currRestaurant.id;
}
Being a post request, if you want to see the data you need to return the full response.
Add {observe: 'response'} to your request like so:
getRestaurant(ID): Observable<HttpResponse<LoggedRestaurant>> {
console.log('ID je razmak' + this.restaurantID);
return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID, {observe:'response'});
}
and retrieve it like so:
this.restaurantService.getRestaurant(this.restaurantID).subscribe(
data => {
this.loggedRestaurant = data.body;
console.log(this.loggedRestaurant)
})
Let me know if that worked :)
Try like this:
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';
#Component({
selector: 'app-informacije',
templateUrl: './informacije.component.html',
styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
restaurant: Restaurant;
loggedRestaurant: LoggedRestaurant;
restaurantID = this.authService.currRestaurant[0].id;
constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }
getRestaurant() {
return this.restaurantService.getRestaurant(this.restaurantID).toPromise().then(data => {
this.loggedRestaurant = data;
});
}
ngOnInit() {
this.restaurant = this.authService.currRestaurant[0];
this.restaurantService.getRestaurant(this.restaurantID).subscribe(
data => {
this.loggedRestaurant = data;
console.log(this.loggedRestaurant)
})
console.log(this.restaurant)
console.log(this.loggedRestaurant)
console.log(this.restaurantService.restaurantID)
}
}
restaurant.service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { AuthService } from './auth.service'
#Injectable({
providedIn: 'root'
})
export class RestaurantService {
private restaurantUrl = 'xxxxxx';
public restaurant: Restaurant;
public loggedRestaurant: LoggedRestaurant
public restaurantID = this.authService.currRestaurant[0].id
constructor(private http: HttpClient, private authService: AuthService) { }
getRestaurant(ID): Observable<LoggedRestaurant> {
console.log('ID je razmak' + this.restaurantID);
return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
}
}

Categories