Sorry for my english if it's very bad, i'm from Russia. I would want ask you. Help me please guys. I have the service in angular 4 and how can i manage it in many components?
This is my service:
import {EventEmitter, Injectable} from '@angular/core';
@Injectable()
export class AuthService {
status: boolean = false;
userAuth: EventEmitter<boolean> = new EventEmitter();
auth() {
this.status = true;
this.userAuth.emit(this.getAuth());
}
logout() {
this.status = false;
this.userAuth.emit(this.getAuth())
}
getAuth() {
return this.status;
}
}
This is my first component. I have already subscribed to service in ngOnInit
import {Component, OnInit} from '@angular/core';
import {ApiService} from "../../service/api/api.service";
import {BlockUI, NgBlockUI} from 'ng-block-ui'
import {AuthService} from "../../service/auth/auth.service";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.less'],
providers: [ApiService, AuthService]
})
export class HeaderComponent implements OnInit {
isLogin: boolean = false;
@BlockUI() blockUI: NgBlockUI;
constructor(private as: ApiService, public authService: AuthService) {
this.blockUI.start();
this.as.isLogin().then((res) => {
if (res.hasError()) return false;
if (res.getResponse().login) this.authService.auth();
if (!res.getResponse().login) this.authService.logout();
// this.isLogin = this.authService.getAuth();
this.blockUI.stop();
});
}
ngOnInit() {
this.authService.userAuth.subscribe((status) => {
this.isLogin = status;
console.log('status', status);
console.log('this.isLogin', this.isLogin);
})
}
logout() {
this.as.logout().then((res) => {
if (res.hasError()) return false;
this.authService.logout();
// this.isLogin = this.authService.getAuth();
});
}
}
But if call the service in another component it'll call new service.
import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms"
import {ApiService} from "../../service/api/api.service";
import {AuthService} from "../../service/auth/auth.service";
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.less'],
providers: [ApiService, AuthService]
})
export class LoginComponent {
formLogin: FormGroup;
constructor(private fb: FormBuilder, private as: ApiService, public authService: AuthService) {
this.formLogin = fb.group({
email: [null, Validators.compose([Validators.required, Validators.pattern(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)])],
password: [null, Validators.compose([Validators.required, Validators.minLength(6)])]
});
}
auth(form) {
this.as.authUser(form).then(res => {
if (res.hasError()) return false;
this.formLogin.reset();
this.authService.auth();
});
}
}