簡體   English   中英

在同一頁面上使用 angular 登錄和注銷

[英]login and logout with angular on the same page

我是角度的新手。 我正在制作一個登錄頁面,但是當我使用 *ngIf 指令時,它沒有按預期工作。 登錄和注銷鏈接必須在變量“logged”更改時消失。 我使用 login.service 來存儲“登錄”狀態和用戶名。

這是代碼。

應用程序組件.html

<h1>{{ title }}</h1> 
<nav>
    <a routerLink="/posts"> Home </a>
    <a *ngIf="!logged" routerLink="/login"> Login </a>
    <a *ngIf="logged" routerLink="/posts" (click) = "logout()"> Logout</a>
</nav>
<router-outlet></router-outlet>

app.component.ts

import { Component} from '@angular/core';
import { LoginService } from './login.service';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'My new Blog!';

  constructor(private loginservice: LoginService){ }

  logout(){
    this.loginservice.logged = false;
    this.loginservice.username ='';

  }

}

登錄.component.html

    <div>
  <h1>Login</h1>
  <input type="text" placeholder="Username*" #username>
  <input type="text" placeholder="Password*" #password>
  <button type="button" (click)="verify_userpass(username.value,password.value)">Submit</button>
  <div>
    <p>{{message}}</p>
  </div>
</div>

登錄.component.ts

    import { Component, OnInit } from '@angular/core';
import { LoginService } from '../login.service';
import { Location } from '@angular/common';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private loginservice: LoginService,private location: Location) { }

  ngOnInit() {
  }

  message: string;
  username: string = 'Admin';
  password: string = 'admin';



  verify_user(username,password){
    if(username===this.username && password===this.password){
      this.loginservice.username = username;
      this.location.back();
      this.loginservice.logged = true;
    }
    else{
      this.message = 'Invalid credentials';
    }
  }

}

登錄.service.ts

    import { Injectable } from '@angular/core';

@Injectable()
export class LoginService {

  username : string;
  logged : boolean;

  constructor() {
  }

}

您的問題是您試圖從 app.component.html 訪問AppComponent類中不存在的AppComponent

您需要公開您的LoginService以便 UI 可以通過更改訪問范圍並將其標記為public來訪問它。

  constructor(public loginService: LoginService){ }

然后,您可以在模板中訪問它,如下所示:

<h1>{{ title }}</h1> 
<nav>
    <a routerLink="/posts"> Home </a>
    <a *ngIf="!loginService.logged" routerLink="/login"> Login </a>
    <a *ngIf="loginService.logged" routerLink="/posts" (click) = "logout()"> Logout</a>
</nav>
<router-outlet></router-outlet>

暫無
暫無

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

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