Angular: Can't return value - javascript

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);
}
}

Related

How do I resolve Circular Dependency in DI Error: NG0200?

This seems to be resolved if I remove HttpClient from PCService and comment out this line:
return this.http.get<PC>(this.pcUrl + "find/" + id);
main-content.component.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Observable } from 'rxjs';
import { PC } from '../../models/pc';
import { PCService } from '../../services/pc.service';
#Component({
selector: 'app-main-content',
templateUrl: './main-content.component.html',
styleUrls: ['./main-content.component.scss']
})
export class MainContentComponent implements OnInit {
pc!: Observable<PC>;
constructor(private route: ActivatedRoute,
private service: PCService) { }
ngOnInit(): void {
this.route.params.subscribe(params =>
{ const id = params['id'];
this.pc = this.service.getPCById(id);
}
);
}
}
pc.service.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { PC } from '../models/pc';
#Injectable({
providedIn: 'root'
})
export class PCService {
constructor(private http: HttpClient) {
}
readonly pcUrl = 'http://localhost:8080/api/v1/pc/';
getPCById(id: number) {
return this.http.get<PC>(this.pcUrl + "find/" + id);
}
}

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();
}
}

Angular returns undefined

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:
restaurant.service.ts
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 = 'https://dm.dnevnimeni.com/dmnew/podacirestorana.php';
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' + this.restaurantID);
return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
}
}
informacije.component.ts
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() {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
});
}
ngOnInit() {
this.getRestaurant();
this.restaurant = this.authService.currRestaurant[0];
console.log(this.restaurant)
console.log(this.loggedRestaurant)
this.restaurantID = this.restaurant.id;
console.log(this.restaurantID)
this.restaurantService.restaurantID =this.restaurantID;
}
}
Update
Your code should be like this
Since you just need to get data you dont have to use post
so you can change from this
return this.http.post<LoggedRestaurant>(this.restaurantUrl, this.restaurantID);
to this
return this.http.get<LoggedRestaurant>(`${this.restaurantUrl}/${this.restaurantID}`);
and add in ngOnInit
ngOnInit() {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
// do something else
});
Because your getRestaurant() method is not called in ngOnInit life cycle hook so the data is not avaibled
You have a few issues with your code. First, you never actually call the getRestaurant() function, thus the service call will never be requested.
Second, you're dealing with asynchronous code and can't expect the service call to be complete before the console.log(this.loggedRestaurant) is run.
My suggestion is that you change your function to return an Observable<LoggedRestaurant> and subscribe to that.
getRestaurant(): Observable<LoggedRestaurant> {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
});
}
Then you can use it as
ngOnInit() {
this.getRestaurant().subscribe(loggedRestaurant => {
console.log(loggedRestaurant);
});
}
Try this:
informacije.component.ts
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;
constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }
getRestaurant() {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
});
}
ngOnInit() {
this.getRestaurant(); // add this line
this.restaurant = this.authService.currRestaurant[0];
console.log(this.restaurant)
console.log(this.loggedRestaurant)
this.restaurantID = this.restaurant.id;
console.log(this.restaurantID)
this.restaurantService.restaurantID =this.restaurantID;
}
}

Rest api call with id parameter in Angular

I have an Angular app which calls a rest api, but that rest api data is defined by which customer it is like: api/incident?customer_id=7 How would I reflect this in the api url or service? and my app? My service is as follows:
import { Injectable } from '#angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse, HttpErrorResponse } from '#angular/common/http';
import { HttpClientModule } from '#angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class
nowService {
serviceApiUrl: string = 'api/incident';
constructor(
private http: HttpClient,
) { }
getAll(): Observable<any> {
return this.http.get<any>(this.serviceApiUrl)
.pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log(error.error.message)
} else {
console.log(error.status)
}
return throwError(
console.log('Something has happened; Api is not working!'));
};
}
component.ts
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '#angular/common/http';
import {HttpClientModule} from '#angular/common/http';
// Services
import { nowService } from '../../services/servicenow.service';
import { Incidents } from '../../models/incidents.model';
#Component({
selector: 'app-service-incident',
templateUrl: './service-incident.component.html',
styleUrls: ['./service-incident.component.scss']
})
export class ServiceIncidentComponent implements OnInit {
public incidents: any;
public loading = true;
public errorApi = false;
constructor(private service: nowService) {
}
ngOnInit() {
this.service.getAll().subscribe((data) => {
this.loading = true;
this.incidents = data.result;
this.loading = false;
console.log('Result - ', data);
console.log('data is received');
})
}
}
So it is based on the customer ID parameter. I just want to know how to do this as I have not come across this before?
Thanks
The code can be as follows:
getAll(customerId): Observable<any> {
return this.http.get<any>(this.serviceApiUrl + "?customer_id" + customerId )
.pipe(
catchError(this.handleError)
);
ngOnInit() {
this.service.getAll(this.customerId).subscribe((data) => {
this.loading = true;
this.incidents = data.result;
this.loading = false;
console.log('Result - ', data);
console.log('data is received');
})
}
Or u can use HttpParams class
example:
https://angular.io/api/common/http/HttpParams
getAll(customerId): Observable<any> {
const params = new HttpParams("customer_id", customerId)
return this.http.get<any>(this.serviceApiUrl ,{ params })
.pipe(catchError(this.handleError));

GET http://localhost:4200/api/x.json 404 (Not Found) - angular 2

Hello, There is a problem with a project that does not recognize a json file - and I do not know why. Is there anything I need to change or make it work?
this is my folders:
this is my service:
import { Injectable } from "#angular/core";
import { Ibrides } from "./brides";
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
#Injectable()
export class brideService {
private _brideUrl = 'api/brides.json';
constructor(private _http: HttpClient) { };
getBrides(): Observable<Ibrides[]> {
return this._http.get<Ibrides[]>(this._brideUrl)
.do(data => console.log('All:' + JSON.stringify(data)))
.catch(this.handleError)
}
private handleError(err: HttpErrorResponse) {
console.log(err.message);
return Observable.throw(err.message);
}
}
this is my component
import { Component, OnInit } from '#angular/core';
import { Ibrides } from "./brides";
import { brideService } from "./brides.service"
#Component({
selector: 'pm-brides',
templateUrl: './brides_list.component.html',
styleUrls: []
})
export class bridesListComponent implements OnInit {
constructor(private _brideService: brideService) {
}
errorMessage: string;
brides: Ibrides[] = [];
ngOnInit(): void {
this._brideService.getBrides()
.subscribe(brides => {
this.brides = brides
},
error => this.errorMessage = <any>error);
}
}
Just reference the file from the root level like this:
_brideUrl = 'app/api/brides.json'
For more information you can refer to this.

Categories