How to notify component when data changes in service - javascript

I have a custom error handler service which gets notified whenever there is an error in the application, now i want to notify a component about the error so that the component will show a error dialog to the user, i have tried event emitter, observer but nothing is notifying the component...
here is my service...
#Injectable()
export class ErrorHandlerService implements ErrorHandler {
public apiError: Subject<any> = new BehaviorSubject(false);
apiError$ = this.apiError.asObservable();
constructor(private errorLogService: ErrorLogService
) {}
handleError(error) {
this.apiError.next(error);
console.log("ERROR = " + error);
};}
And the component...
#Component({
selector: 'app-error-log',
templateUrl: './error-log.component.html',
styleUrls: ['./error-log.component.scss'],
providers: [ErrorLogService]
})
export class ErrorLogComponent implements OnInit {
constructor(
private errorHandlerService: ErrorHandlerService
) {
this.errorHandlerService.apiError$.subscribe(data => {
alert("error in component = " + data);
});
}
onNoClick(): void {
// this.dialogRef.close();
}
ngOnInit() {
this.errorHandlerService.apiError$.subscribe(data => {
alert("error in component = " + data);
});
}
}

Method with Following format can give an output of service execution is successful or not. Hope the following code will help you
//Code in service.ts
#Injectable()
export class ErrorHandlerService implements ErrorHandler {
public apiError: Subject<any> = new BehaviorSubject(false);
apiError$ = this.apiError.asObservable();
constructor(private errorLogService: ErrorLogService
) { }
private handleError(error) {
return Observable.throw(error.json().msg || 'Server error');
}
_forgotPassword(userId, passwords, isResetPwd) {
return this.http.post(this.forgotPasswordUrl,
{
userId: userId,
passwords: passwords,
isResetPwd: isResetPwd
})
.map(res => res.json())
.catch(this.handleError);
}
}
//Code in component class file
this.errorHandlerService._forgotPassword(userId, passwords, isResetPwd).
subscribe(data => {
// Code here.....
});

This is how i have fixed it...
app.component.html
<error-log></error-log>
error-log.component
import { Component, OnInit } from '#angular/core';
import { ErrorLogService } from './error-log.service';
#Component({
selector: 'error-log',
templateUrl: './error-log.component.html',
styleUrls: ['./error-log.component.scss']
})
export class ErrorLogComponent implements OnInit {
constructor(private errorLogService: ErrorLogService) { }
ngOnInit() {
this.errorLogService.apiEvent.subscribe(data =>{
alert("error in errorlog component through errorLogService event emitter = " + data);
})
this.errorLogService.apiError$.subscribe(data =>{
alert("error in errorlog component errorLogService = " + data);
})
}
}
error-handler.service
import { Injectable, ErrorHandler} from '#angular/core';
import { ErrorLogService } from './error-log.service';
#Injectable()
export class ErrorHandlerService implements ErrorHandler {
constructor(private errorLogService: ErrorLogService
) {}
handleError(error) {
this.errorLogService.setError(error);
};}
error-log.service
import { Injectable, ErrorHandler, EventEmitter, Output} from '#angular/core';
import { EventListener } from '#angular/core/src/debug/debug_node';
import { ReplaySubject} from 'rxjs/Rx';
#Injectable()
export class ErrorLogService {
public apiError: ReplaySubject<any> = new ReplaySubject();
public apiEvent:EventEmitter<any> = new EventEmitter();
public apiError$ = this.apiError.asObservable();
constructor() {
// super();
}
setError(error){
this.apiEvent.emit(error);
this.apiError.next(error);
// super.handleError(error);
console.log("ERROR = " + error);
} }
No idea why i cant raise an event directly from error-handler.service

if you initialize the component after the service recieve the errors then he can only emit errors that's being recieved after his init.
user ReplaySubject to emit all previous errors aswell
#Injectable()
export class ErrorHandlerService implements ErrorHandler {
public apiError: ReplaySubject<any> = new ReplaySubject();
apiError$ = this.apiError.asObservable();
constructor(private errorLogService: ErrorLogService
) {}
handleError(error) {
this.apiError.next(error);
console.log("ERROR = " + error);
};}

Related

Angular 6 : Issue of component data binding

I call service which make http call, I assign response to component variable now when I try access that component variable to view it display blank.
Means component variable assign in subscribe successfully but cant acceess in html view.
I think view is loaded before values assign to component data.
component
import {Component, OnInit, ChangeDetectionStrategy} from '#angular/core';
import { UserService } from '../../../../../core/services/users/user.service';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'm-user-list',
templateUrl: './user-list.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserListComponent implements OnInit {
list;
roles = {};
current_page: any
totalRecords: any
public showContent: boolean = false;
constructor(private userService: UserService, private http: HttpClient) {
}
ngOnInit() {
this.getRecords();
}
getRecords(){
this.getResultedPage(1);
}
getResultedPage(page){
return this.userService.getrecords()
.subscribe(response => {
this.list = response.data;
});
}
}
Service
import { Injectable } from '#angular/core';
import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpParams , HttpErrorResponse, HttpHeaders } from '#angular/common/http';
import { map, catchError, tap, switchMap } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
import { UtilsService } from '../../services/utils.service';
import { AppConfig } from '../../../config/app'
#Injectable({
providedIn: 'root'
})
export class UserService{
public appConfig: AppConfig;
public API_URL;
constructor(private http: HttpClient, private util: UtilsService) {
this.appConfig = new AppConfig();
this.API_URL = this.appConfig.config.api_url;
}
private extractData(res: Response) {
let body = res;
return body || { };
}
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
return throwError('Something bad happened; please try again later.');
};
getrecords(): Observable<any> {
return this.http.get('/api/users', httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
}

How to approach multiple async requests from back-end in Angular 6?

I am new to Angular and having hard time grasping how to deal with async requests.
I have 3 components:
parent - AppComponent
children - LoginComponent,NavbarComponent,DashboardComponent,MainComponent,SidebarComponent
and one AuthService
On pressing "Login" button at the logging component I need to transfer boolean "true" value to all components.
On pressing "Logout" button at the navbar component I need to transfer boolean "false" value to all components and set user=null
if true ->
set token in localStorage with user ID
preform http.get("http://localhost:3000/user/"+id) request to retrieve full user info and inject user info to Dashboard,Main,Sidebar,App and Navbar components.
The problem is that whenever I logout the false/true value updates on all components immediately but the user info does not turn into null unless I refresh the page or send it with router to another component and then return to MainComponent, same thing with new login.
How do I update both user info and status in all components immediately without refreshing the page?
authService:
import { Injectable } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { Router } from "#angular/router";
import { User } from "../models/User";
#Injectable({ providedIn: "root" })
export class AuthService {
user: User;
private _url = "http://localhost:5000/user/";
constructor(private http: HttpClient, private _router: Router) {}
registerUser(user) {
return this.http.post<any>(this._url + "register", user);
}
loginUser(user) {
return this.http.post<any>(this._url + "login", user);
}
logoutUser() {
localStorage.clear();
this._router.navigate(["/"]);
}
loggedIn() {
return !!localStorage.getItem("token");
}
getToken() {
return localStorage.getItem("token");
}
getCurrentUser() {
return this.http.get<any>("http://localhost:5000/shop/current");
}
}
Main/Sidebar component:
import { Component, OnInit, DoCheck } from "#angular/core";
import { AuthService } from "src/app/services/auth.service";
import { User } from "src/app/models/User";
#Component({
selector: "app-sidebar",
templateUrl: "./sidebar.component.html",
styleUrls: ["./sidebar.component.css"]
})
export class SidebarComponent implements OnInit, DoCheck {
isSidenavOpen: boolean = true;
user: User;
constructor(private _authService: AuthService) {}
ngOnInit() {
if (this._authService.loggedIn()) this._authService.getCurrentUser().subscribe(res => (this.user = res.user));
else this.user = null;
}
ngDoCheck() {
if (!this._authService.loggedIn()) this.user = null;
}
}
login:
constructor(private _authService: AuthService, private _router: Router) {}
// onLoginUser() {
// this._authService.loginUser(this.loginUserData).subscribe(
// res => {
// localStorage.setItem("token", res.token);
// localStorage.setItem("user", res.user._id);
// this._router.navigate(["/"]);
// },
// err => console.log(err)
// );
// }
}
Use event EventEmitter to emit event on login, logout etc and listen in each component, that depends on user data.
In service, where you call logoutUser, loginUser methods of AuthService:
// LoginService
userLoggin: EventEmitter<User> = new EventEmitter();
userLoggout: EventEmitter<any> = new EventEmitter();
constructor(private _authService: AuthService, private _router:
Router) {}
loginUser() {
this._authService.loginUser(this.loginUserData).subscribe(
res => {
localStorage.setItem("token", res.token);
localStorage.setItem("user", res.user._id);
this.userLoggin.emit(res.user);
this._router.navigate(["/"]);
},
err => console.log(err)
);
}
logoutUser() {
this._authService.logoutUser().subscribe(
res => {
this.userLoggout.emit();
},
err => console.log(err)
);
}
}
Then in component:
import { Component, OnInit, DoCheck } from "#angular/core";
import { AuthService } from "src/app/services/auth.service";
import { User } from "src/app/models/User";
import { LoginService } from "src/app/services/login.service";
#Component({
selector: "app-sidebar",
templateUrl: "./sidebar.component.html",
styleUrls: ["./sidebar.component.css"]
})
export class SidebarComponent implements OnInit, DoCheck {
isSidenavOpen: boolean = true;
user: User;
loggin$: Subscription;
logout$: Subscription;
constructor(private _authService: AuthService, private _loginService: LoginService) {
this.loggin$ = this._loginService.userLoggin.subscribe(user => {
this.user = user;
});
this.logout$ = this._loginService.userLoggout.subscribe(user => {
this.user = null;
});
}
ngOnInit() {
}
ngOnDestroy() {
this.loggin$.unsubscribe();
this.logout$.unsubscribe();
}
}

Angular - communication from child-component to parent

I don't get i, how to communicate between components and services.. :(
I have read and tried a lot about even if some examples somehow work, I do not understand why (?)
what I want to achieve:
I have one parent and two child-components:
dashboard
toolbar
graph
in the toolbar-component I have a searchfield, which gets it's result from a external source (works via service).. when the result arrives, I need to trigger the updateGraph()-Method in the graph-component
toolbar.component.ts
import { Component, OnInit, Output, EventEmitter } from '#angular/core';
import { FormControl } from '#angular/forms';
import { WebsocketsService } from '../../../services/websockets/websockets.service';
import { DataService } from '../../../services/data/data.service';
#Component({
selector: 'toolbar',
templateUrl: './toolbar.component.html',
styleUrls: ['./toolbar.component.scss'],
providers: [WebsocketsService, DataService]
})
export class ToolbarComponent implements OnInit {
#Output() newGraphData: EventEmitter<boolean> = new EventEmitter();
searchField: FormControl;
search: string;
private isNewGraph = false;
constructor(private _websocketsService: WebsocketsService, private _dataService: DataService) {
}
ngOnInit() {
this.searchField = new FormControl();
this.searchField.valueChanges
.subscribe(term => {
this.search = term;
});
}
private applySearch() {
const res = this._websocketsService.sendQuery(this.search);
this._dataService.setGraphData(res);
this.newGraphData.emit(true);
this.search = '';
this.searchField.reset();
}
}
graph-component.ts
import { Component, OnInit} from '#angular/core';
import { HttpService } from '../../../services/http/http.service';
import { DataService } from '../../../services/data/data.service';
#Component({
selector: 'graph',
templateUrl: './graph.component.html',
styleUrls: ['./graph.component.scss'],
providers: [HttpService, DataService]
})
export class GraphComponent implements OnInit, AfterViewInit {
constructor( private _httpService: HttpService, private _dataService: DataService ) {
}
ngOnInit() {
}
public renderResult() {
console.log( this._dataService.getGraphData() );
}
}
data.service.ts
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs/Subject';
#Injectable()
export class DataService {
private graphData: Subject<string> = new Subject<string>();
public setGraphData(data) {
this.graphData.next( data );
}
public getGraphData() {
return this.graphData;
}
constructor() { }
}
I simply want ´renderResult()´to be executed after the searchresult has been written to ´graphData´. please help i am confused.
If I understand, you want communication between components and service.
A[component] (make a information) -----(notification)-----> B[service] ----(send)----> C[component] (consume the information)
It's correct? Let's go.
You need create a subscription of graphData(data.service.ts) in GraphComponent.
import { Subscription } from 'rxjs/Subscription';
export class GraphComponent implements OnInit, AfterViewInit {
constructor( private _httpService: HttpService, private _dataService: DataService ) {
}
private subscription: Subscription;
ngOnInit() {
this.subscription = this._dataService.getGraphData().asObservable().subscribe((data) => {
console.log(data);
});
}
}
Look here to help you.
http://jasonwatmore.com/post/2016/12/01/angular-2-communicating-between-components-with-observable-subject
Short answer, I think you need to subscribe to the getGraphData subject, something like this (NOT RECOMMENDED):
public renderResult() {
this._dataService.getGraphData().subscribe(d => {
console.log(d)
});
}
It is not recommended as per the lead of RxJS says: https://medium.com/#benlesh/on-the-subject-of-subjects-in-rxjs-2b08b7198b93
Better answer, create an observable in your service and subscribe to that instead.
data.service.ts
graphObservable = this.graphData.asObservable();
graph-component.ts
public renderResult() {
this._dataService.graphObservable().subscribe(d => {
console.log(d)
});
}

Angular 5 component expecting an argument

Im trying a simple profile app, and all the sudden Im getting error TS2554
ERROR in /app/components/profile/profile.component.ts(25,3): error TS2554: Expected 1 arguments, but got 0.
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../../services/auth.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '#angular/router';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: Object;
constructor(
private auth: AuthService,
private flashMsg: FlashMessagesService,
private router: Router
) {
}
ngOnInit() {
this.auth.getProfile().subscribe( profile => {
this.user = profile.user;
},
err => {
return false;
});
}
}
auth.service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
import { tokenNotExpired } from 'angular2-jwt';
#Injectable()
export class AuthService {
authToken: any;
user: any;
constructor(
private http: Http
) {
}
getProfile(user) {
let headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type','application/json');
return this.http.get('http://localhost:3000/users/profile', {headers:headers})
.map(res => res.json());
}
loadToken() {
const token = localStorage.getItem('id_token');
this.authToken = token;
}
}
Your getProfile is expecting an argument named user but you are not passing it from the component
You need to pass an argument as follows,
this.auth.getProfile(user).subscribe( profile => {
this.user = profile.user;
},
err => {
return false;
});
or if you don't need an argument , remove it from your service method.

render html after completion process of component in angular2

I am calling a api in my app component after getting the response I can decide which div is to show and which div is to hide.
But it render the html before completion of component process.
Below are the code example.
user.service.ts
import { Injectable } from '#angular/core';
import {Http,Headers, RequestOptions, Response, URLSearchParams} from '#angular/http';
#Injectable()
export class UserService {
private static isUserLoggedIn: boolean = false;
private userData: any;
constructor(private http: Http) { }
public isLoggedIn() {
return UserService.isUserLoggedIn;
}
public getUserData() {
return this.userData;
}
setUserData() {
var url = 'http://api.example.in/user/logincheck';
this.http
.get(url)
.map(response => response.json())
.subscribe(
(data) => {
this.userData = data;
if (typeof this.userData.id != 'undefined' && this.userData.id > 0) {
UserService.isUserLoggedIn = true;
}
},
(err) => { throw err; }
);
}
}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { UserService } from './services/user/user.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [UserService],
})
export class AppComponent {
constructor(private userService: UserService) {
this.userLoggedInCheck();
}
ngOnInit() {
}
userLoggedInCheck() {
this.userService.setUserData();
}
}
I want here to load html after complete of userLoggedInCheck function called.
return a true value from userLoggedInCheck if the necessary conditions are met and assign it to a variable in the app.component.ts file. In the html file place the content within an *ngIf based on the return variable from the function.
for eg.
userLoggedInCheck() {
this.showHtml = this.userService.setUserData();
}
and in html
<div *ngIf="showHtml">
....... // code
</div>

Categories

Resources