首页 文章

是否每个动作都需要Angular 6中的一个组件

提问于
浏览
0

我是Angular的新手,

我已经使用JWT成功编写了一个登录系统(Backend是PHP / Lumen) .

当我登录时,我将用户信息存储在本地存储中 .

localStorage.setItem('currentUser', JSON.stringify({email, token: res.token}));

所以,基本上,logout只是删除这个文件,一行代码 .

是否有必要为注销操作创建整个组件?

对我来说似乎很重要 .

你能给我一个更简单的方法吗?我真的不知道应该如何组织它 .

2 回答

  • 1

    我个人的意见是你必须为这种情况使用某种服务,这样你就可以将它注入你需要的任何组件中 .

    服务可以是这样的

    import { Injectable } from "@angular/core";
    
    @Injectable()
    export class AuthService {
    
      constructor() {}
    
      logout() {
          this.cookies.delete() // this line is pseudo code
      }
    }
    

    更新:

    你可以这样称呼它

    import { Component, Input, OnDestroy, OnInit } from "@angular/core";
    import { AuthService } from "./some-service path";
    
    @Component({
      selector: "app-recursive",
      templateUrl: "./recursive.component.html",
      styleUrls: ["./recursive.component.css"]
    })
    export class RecursiveComponent implements OnDestroy, OnInit {
      nextLayer = [];
    
      constructor(private auth: AuthService) {}
    
      ngOnInit() {
    
      }
    
      logoutFunc() {
        this.auth.logout(); // If we asume that you have logout method in the service
      }
    
    }
    

    在这里你可以深入了解服务背后的逻辑TourOfHeroesServicesChapter,我也建议你去英雄之旅的每个部分,有很多有用的东西

  • 0

    您不需要为每个操作都拥有组件 . 由于您的注销位于导航栏中,因此您可以在导航栏组件中编写并执行所有必要操作,以使其保持井井有条

相关问题