简体   繁体   中英

Return object in Observable (Angular)

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'
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM