簡體   English   中英

以角度返回錯誤時的最佳做法是什么

[英]What is the best practice when returning errors in angular

我有一個角度應用程序。 在這個應用程序中,我有一個AuthService AuthService針對AuthService身份驗證登錄一個用戶。

我的問題如下:

如果登錄成功,您認為導航到成功頁面是服務的責任嗎? 還是應該是調用服務的組件?

如果出現錯誤(如我的情況下無效密碼),您將如何將此信息返回給組件以將其顯示給用戶?

我的服務:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { User } from 'firebase';

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    user: User;
    constructor(public afAuth: AngularFireAuth, public router: Router) {
        this.afAuth.authState.subscribe(user => {
            if (user) {
                this.user = user;
                localStorage.setItem('user', JSON.stringify(this.user));
            } else {
                this.user = null;
                localStorage.setItem('user', null);
            }
        });
    }

    async login(email: string, password: string) {
        let result = await this.afAuth.auth.signInWithEmailAndPassword(
            email,
            password
        );
        this.router.navigate(['...']); 
    }
}

我的組件:

import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
import { NgForm } from '@angular/forms';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent  {

    constructor(private authService: AuthService) { }

    onSubmit(form: NgForm) {
        this.authService.login(form.value.email, form.value.password);
    }

}

回答你的問題

如果登錄成功,您認為導航到成功頁面是服務的責任嗎? 還是應該是調用服務的組件?

對於相應的干凈代碼,我認為您需要處理服務中的導航邏輯,因為有時您的組件會增長並且您的代碼庫很難維護。 或者我建議您對 NGRX 庫進行研究,它們具有 1 層調用效果,因此您可以在其中為您的應用程序執行副作用邏輯,而服務類僅調用 API。

如果出現錯誤(如我的情況下無效密碼),您將如何將此信息返回給組件以將其顯示給用戶?

和我上面的選項一樣。 並建議您采用副作用方法,因為 API 錯誤也將在效果類中處理

以下是我的應用程序示例。 當我收到成功登錄操作時,我會將用戶登錄重定向到門戶頁面。 要完全理解這種模式,您可以看一下這張圖片

在此處輸入圖片說明

一個組件是分派一個動作。 如果我們需要一些副作用(比如在這個例子中,如果用戶登錄成功,將用戶重定向到門戶頁面),動作將被效果處理。 然后,reducer 將根據操作類型和來自組件或效果端的數據計算新狀態,然后它會更新 UI 以反映更改。

@Effect({dispatch: false})
  loginSuccess$ = this
    .actions$
    .pipe(ofType(authAction.LoginActionTypes.LOGIN_SUCCESS), tap(() => this.router.navigate(['/portal'])));

您可以在此處查看我的完整示例和NGRX

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM