将OKTA可观察到可用的字符串变量转换

发布于 2025-02-09 17:41:58 字数 5039 浏览 2 评论 0原文

我正在尝试在Angular 12中创建一个返回“用户”的服务。我正在使用Okta进行身份验证。

我只想简化这一点...我可以将姓氏作为可以观察到的:

let familyName = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.idToken?.claims.family_name ?? '')
    );

但是我只想传递一个字符串,而不是整个可观察的。

例如,我现在可以通过使用familyName将FamilyName使用为HTML

{{familyName | async}}

,但是我希望没有可观察到的变量。

这是我的文件以供参考(是的,我知道它们是笨拙的)。

user.service.ts

import {Inject, Injectable} from '@angular/core';
import {OKTA_AUTH, OktaAuthStateService} from '@okta/okta-angular';
import {filter, map, Observable, of, Subscription} from 'rxjs';
import {AccessToken, AuthState, OktaAuth} from '@okta/okta-auth-js';
import {User} from './data/user.model';

@Injectable({
  providedIn: 'root'
})

export class UserService {

  constructor(
    private _oktaAuthStateService: OktaAuthStateService,
    @Inject(OKTA_AUTH) private _oktaAuth: OktaAuth
  ) { }

  get user(): Observable<any> {

    let name = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.idToken?.claims.name ?? '')
    );

    let email = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.idToken?.claims.email ?? '')
    );

    let familyName = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.idToken?.claims.family_name ?? '')
    );

    let givenName = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.idToken?.claims.given_name ?? '')
    );

    let stringName = name.subscribe(value => {
      return value.toString();
    })

    let accessToken = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.accessToken?.accessToken ?? '')
    );

    let obsof5: Observable<User>;
    obsof5 = of<User>({
      'email': email,
      'name': name,
      'givenName': givenName,
      'familyName': familyName,
      'accessToken': accessToken,
      'tenancy': [],
      'tenantIds': []
    });
    return obsof5;
  }
}

app.component.ts

import { Component, Inject, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { OktaAuthStateService, OKTA_AUTH } from '@okta/okta-angular';
import {AccessToken, AuthState, OktaAuth} from '@okta/okta-auth-js';
import {filter, map, Observable, Subscription} from 'rxjs';
import { UserService } from './user.service';
import {UserTenancy} from './data/user.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'okta-angular-quickstart';
  public isAuthenticated$!: Observable<boolean>;
  public name: Observable<string> | undefined;
  email: Observable<string> | undefined;
  givenName: Observable<string> | undefined;
  familyName: Observable<string> | undefined;
  accessToken: Observable<"" | AccessToken> | undefined;


  constructor(private _router: Router,
              private _oktaStateService: OktaAuthStateService,
              @Inject(OKTA_AUTH) private _oktaAuth: OktaAuth,
              private userService: UserService
  ) { }

  public ngOnInit(): void {
    this.isAuthenticated$ = this._oktaStateService.authState$.pipe(
      filter((s: AuthState) => !!s),
      map((s: AuthState) => s.isAuthenticated ?? false)
    );

    this.userService.user.subscribe(
        (value) => {
          console.log("value", value);
          this.name = value.name;
          this.email = value.email;
          this.givenName = value.givenName;
          this.familyName = value.familyName;
          this.accessToken = value.accessToken;
      }
    );
  }

  public async signIn() : Promise<void> {
    await this._oktaAuth.signInWithRedirect().then(
      _ => this._router.navigate(['/profile'])
    );
  }

  public async signOut(): Promise<void> {
    await this._oktaAuth.signOut();
  }
}

app.component.html

  <h1>Hello world - here's where you are</h1>
  <p>Name: {{name | async}}</p>
  <p>Email: {{email | async}}</p>
  <p>FamilyName: {{familyName | async}}</p>
  <p>GivenName: {{givenName | async}}</p>
  <p>AccessToken: {{accessToken | async}}</p>
  <p>Is Authenticated: {{isAuthenticated$ | async}}</p>

I am trying to create a service in Angular 12 that returns a "User". I'm using OKTA for authentication.

I would just like to simplify this... I can get the family name as an Observable like this:

let familyName = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.idToken?.claims.family_name ?? '')
    );

But I would like to just pass a string - not the whole observable.

For example, I can now use familyName into HTML by doing

{{familyName | async}}

but I would like the variable without the observable.

Here's my files for reference (and yes I know they're clunky).

user.service.ts

import {Inject, Injectable} from '@angular/core';
import {OKTA_AUTH, OktaAuthStateService} from '@okta/okta-angular';
import {filter, map, Observable, of, Subscription} from 'rxjs';
import {AccessToken, AuthState, OktaAuth} from '@okta/okta-auth-js';
import {User} from './data/user.model';

@Injectable({
  providedIn: 'root'
})

export class UserService {

  constructor(
    private _oktaAuthStateService: OktaAuthStateService,
    @Inject(OKTA_AUTH) private _oktaAuth: OktaAuth
  ) { }

  get user(): Observable<any> {

    let name = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.idToken?.claims.name ?? '')
    );

    let email = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.idToken?.claims.email ?? '')
    );

    let familyName = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.idToken?.claims.family_name ?? '')
    );

    let givenName = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.idToken?.claims.given_name ?? '')
    );

    let stringName = name.subscribe(value => {
      return value.toString();
    })

    let accessToken = this._oktaAuthStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState),
      map((authState: AuthState) => authState.accessToken?.accessToken ?? '')
    );

    let obsof5: Observable<User>;
    obsof5 = of<User>({
      'email': email,
      'name': name,
      'givenName': givenName,
      'familyName': familyName,
      'accessToken': accessToken,
      'tenancy': [],
      'tenantIds': []
    });
    return obsof5;
  }
}

app.component.ts

import { Component, Inject, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { OktaAuthStateService, OKTA_AUTH } from '@okta/okta-angular';
import {AccessToken, AuthState, OktaAuth} from '@okta/okta-auth-js';
import {filter, map, Observable, Subscription} from 'rxjs';
import { UserService } from './user.service';
import {UserTenancy} from './data/user.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'okta-angular-quickstart';
  public isAuthenticated$!: Observable<boolean>;
  public name: Observable<string> | undefined;
  email: Observable<string> | undefined;
  givenName: Observable<string> | undefined;
  familyName: Observable<string> | undefined;
  accessToken: Observable<"" | AccessToken> | undefined;


  constructor(private _router: Router,
              private _oktaStateService: OktaAuthStateService,
              @Inject(OKTA_AUTH) private _oktaAuth: OktaAuth,
              private userService: UserService
  ) { }

  public ngOnInit(): void {
    this.isAuthenticated$ = this._oktaStateService.authState$.pipe(
      filter((s: AuthState) => !!s),
      map((s: AuthState) => s.isAuthenticated ?? false)
    );

    this.userService.user.subscribe(
        (value) => {
          console.log("value", value);
          this.name = value.name;
          this.email = value.email;
          this.givenName = value.givenName;
          this.familyName = value.familyName;
          this.accessToken = value.accessToken;
      }
    );
  }

  public async signIn() : Promise<void> {
    await this._oktaAuth.signInWithRedirect().then(
      _ => this._router.navigate(['/profile'])
    );
  }

  public async signOut(): Promise<void> {
    await this._oktaAuth.signOut();
  }
}

app.component.html

  <h1>Hello world - here's where you are</h1>
  <p>Name: {{name | async}}</p>
  <p>Email: {{email | async}}</p>
  <p>FamilyName: {{familyName | async}}</p>
  <p>GivenName: {{givenName | async}}</p>
  <p>AccessToken: {{accessToken | async}}</p>
  <p>Is Authenticated: {{isAuthenticated$ | async}}</p>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痴者 2025-02-16 17:41:58

1-您声明familyName:string;familyName $:observable&lt; string&gt ;;是组件类中的全局变量。

2-然后,您以的相同方式定义familyname $ iSauthenticated $

this.familyName$ = this._oktaStateService.authState$.pipe(...

3- yuo subscribe familyname $ yu yuo namyname $,并将传入的价值发送给familyName作为folwing:

this.familyName$.subscribe(
  (fName) => { this.familyName = fName}
);

现在您将familyName $ as as familyName $ as as FamilyName $可观察到的家庭名称为普通字符串,因此您可以根据需要使用它们。

1- you declare familyName : string; and familyName$ : Observable<string>; as a global variable in the component class.

2- then you define familyName$ in the same way of isAuthenticated$

this.familyName$ = this._oktaStateService.authState$.pipe(...

3- Yuo subscribe familyName$ and sent the incoming value to familyName as folwing:

this.familyName$.subscribe(
  (fName) => { this.familyName = fName}
);

now you have familyName$ as a observable and familyName as a normal string, so you can use them as you need.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文