简体   繁体   English

Angular - 如何从我的服务组件中的订阅返回布尔值?

[英]Angular - How to return a bool from a Subscription in my service-component?

I have a login.service.ts, and my login.component.ts我有一个 login.service.ts 和我的 login.component.ts

In my login component, I have an input field, where the user inputs a username, and when he hits "login", we check if that user name is valid with this call:在我的登录组件中,我有一个输入字段,用户在其中输入用户名,当他点击“登录”时,我们通过此调用检查该用户名是否有效:

<button color="primary" mat-raised-button (click)="loadUserInfo(email.value)">
      continue
      <mat-icon>arrow_forward</mat-icon>
    </button>

loadUserInfo(userLogin: string) {
this.loginService.processLogin(userLogin);
}

which calls my service:调用我的服务:

processLogin(loginId: string) {
return this.http.get("api/" + loginId).subscribe(
(user: User) => {

        this.userSub.next(user);
      },
      err => {
        console.error("Username not valid");
      }
    );
  }

I cannot wrap my head around the following: If the call is unsuccessful, and there is no user with that username, how can I, in my login.component.ts , show a error message under the input field?我无法解决以下问题:如果调用不成功,并且没有使用该用户名的用户,我如何在我的login.component.ts中在输入字段下显示错误消息? I would need a bool or something, but the error handling is in the service component , so not really sure what is the best way我需要一个 bool 或其他东西,但错误处理在service component中,所以不确定什么是最好的方法

I would put under my input field this:我会把这个放在我的输入字段下:

  <div *ngIf="userNotValid"> Error, this user doesn't exist</div>

But what should be the best way to handle this scenario?但是处理这种情况的最佳方法应该是什么? The users presses the button, the API returns the error, and now, how do I show an error in the login-component html file?用户按下按钮,API 返回错误,现在,如何在登录组件 html 文件中显示错误? Thank you谢谢

A BehaviorSubject is used to store a variable. BehaviorSubject用于存储变量。 It works just like an Observable but you can access its latest value whenever you want.它就像一个Observable一样工作,但你可以随时访问它的最新值。

The async pipe is used to render values from asynchronous sources such as Observable or BehaviorSubject or a Subject . async pipe 用于呈现来自异步源(例如ObservableBehaviorSubjectSubject )的值。

Note: a Subject does not store the latest value as opposed to a BehaviorSubject .注意:与BehaviorSubject不同, Subject不存储最新值。

Service服务

public error$ = new BehaviorSubject(false);

....

this.error.next(true); // to trigger a new error

Component零件

<div *ngIf="service.error$ | async">Error<div>

as many suggested, I should make it an observable in my service, and subscribe to it from my component, I didn't want to do this as I would need to change other stuff as well, but if it's the cleanest way I just might do it.正如许多人建议的那样,我应该在我的服务中使其成为可观察的,并从我的组件订阅它,我不想这样做,因为我还需要更改其他东西,但如果这是最干净的方式,我可能做吧。

Would it make sense, doing it like this, so it both returns a boolean, and if the User is valid, it will fire next() to my behaviourSubject that stores the current user?这样做有意义吗,所以它都返回behaviourSubject ,如果用户有效,它会触发 next() 到存储当前用户的我的 behaviorSubject?

processLogin(loginId: string): Observable<boolean> {
    return this.http.get("api/" + loginId).pipe(map(
      (info: UserInfo) => {
        console.log("userinfo:", info);
        return info;
      }),
      catchError(err => of(null as UserInfo))
    ).pipe(tap(
      uInfo => {
        this.userSub.next(uInfo);
      }
    ),
    map(u => u != null)
    );
  }

am I doing this correctly?我这样做正确吗? Or could I improve it?或者我可以改进它吗? In my view, now I have both things I wanted, a Boolean as return, and in case of Existing user, it will next() the value.在我看来,现在我有两个我想要的东西,一个 Boolean 作为回报,如果是现有用户,它将next()值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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