1

I have a big project with Authentication but now it's turned off. I can see "/admin" page and everything, but there are some blocks with *ngIf="isAdmin" which comes from authentication.server. I need to set Admin user as a default and don't check it from base when Authentication is turned off so I can see all block's. I know that should make a check and set a default user in get(): Observable<User> {} but don't understand how to make it in correct way. I thought at first that just create new User() with role = "UserRole.Admin" but can't return simple object cause of Observable. In which way I need to return default user? Would be really grateful for any help!

Here's my code:

in components its look like this:

this.authentificationService.get()
  .subscribe((user: User) => this.isAdmin = user.role.name === UserRole.Admin);

authentication.server.ts

import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from '../shared/models/user';

@Injectable()
export class AuthenticationService {
  private backEndUrl = 'api/user';

  constructor(private http: HttpClient) { }
  get(): Observable<User> {
// need to return default User here in correct format
    return  this.http.get<User>(this.backEndUrl)
  }
}

User.ts

import { UserRole } from '../user-role.enum';
export class Role {
  constructor(id: number, name: UserRole) {}
}

export class User {
  constructor(
    id: number = null,
    firstName: string = '',
    lastName: string = '',
    email: string = '',
    role: Role = null
}

User-role.enum.ts

export enum UserRole {
  Admin = 'Admin',
  Manager = 'Manager',
  User = 'User'
}

1 Answer 1

3

I thought at first that just create new User() with role = "UserRole.Admin" but can't return simple object cause of Observable.

You are quite close you need to wrap your user inside observable. eg

const user = new User();
return Observable.of(user);

1
  • 2
    For Rxjs v6+ import { of } from 'rxjs'; Commented May 9, 2020 at 16:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.