【问题标题】:How can I show data in an Angular component in Angular 10?如何在 Angular 10 的 Angular 组件中显示数据?
【发布时间】:2021-02-26 00:10:19
【问题描述】:

我从 Angular 10 开始,我想将当前用户放在 profile.component.html 中,并将导航栏放在 app.component.html 中。这是代码。

users.ts

export interface User {
    username : string
    password: string
    edad: number
    fechaNacimiento: string
    createdAt?: string
    updatedAt?: string
    id?:number
}

login.component.ts

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { UsersService } from 'src/app/services/users.service';


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

  constructor(
    public usersServices: UsersService,
    private router: Router
  ) { }

  ngOnInit(): void {
  }

  login(form: NgForm){
    this.usersServices.login(form.value).subscribe(
      res => {
        console.log(res);
        localStorage.setItem('token',res['token']);
        this.router.navigate(['/profile',form.controls['username'].value],{
          state:{username:form.controls['username']}
        });
      },
      err => {
        console.log(err)
      }
    )
  }


}

profile.component.ts

import { Component, OnInit } from '@angular/core';
import { UsersService } from '../../services/users.service';
import { NgForm } from '@angular/forms';
import { User } from 'src/app/models/users';
import { ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {

  constructor(public usersService: UsersService,private route: ActivatedRoute) { 
    this.route.params.subscribe(username => {
      console.log(username);
    })
  }

  ngOnInit(): void {
    this.getUsers();
  }

  getUsers(){
    this.usersService.getUsers().subscribe(
      res => {
        this.usersService.user = res
      },
      err => console.log(err)
    )
  }

  
  deleteUser(id:number){
    if(confirm('Are  you sure you want to delete it?')){
      this.usersService.deleteUser(id).subscribe(
        (res) => {
          this.getUsers();
        },
        (err) => console.log(err)
      );
    }

  }

  updateUser(form: NgForm){
    this.usersService.editUser(form.value).subscribe(
      res => console.log(res),
      err => console.log(err)
    );
  }
}

<div class="col-md-8">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Username</th>
                <th>Age</th>
                <th>Birthdate</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let user of usersService.user">
                <td>{{user.username}}</td>
                <td>{{user.edad}}</td>
                <td>{{user.fechaNacimiento}}</td>
                <td>
                    <button class="btn btn-secondary btn-sm" data-toggle="modal" data-target="#staticBackdrop">
                        <i class="material-icons">edit</i>
                    </button>
                    <button class="btn btn-danger btn-sm" (click)="deleteUser(user.id)">
                        <i class="material-icons">delete</i>
                    </button>
                 </td>
        </tbody>
    </table>
</div>


app.component.html

<nav class="navbar navbar-dark bg-dark">
  <div class="container">
    <a class="navbar-brand" href="#">MEAN Users</a>
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" routerLink="/profile" routerLinkActive = "active">Profile</a>
      </li>
    </ul>
    <ul class="navbar-nav ml-auto">
      <ng-container *ngIf="!usersService.loggedIn(); else loggedIn">
        <li class="nav-item">
          <a class="nav-link" routerLink="/register" routerLinkActive = "active">Signup</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="/login" routerLinkActive = "active">Signin</a>
        </li>
      </ng-container>
      <ng-template #loggedIn>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle"  data-toggle="dropdown"  role="button" style="cursor: pointer;"></a>
          <div class="dropdown-menu">
            <a class="dropdown-item" (click)="usersService.logout()">Logout</a>
          </div>
        </li>
      </ng-template>

    </ul>
  </div>
</nav>

<div class="container p-5">
  <router-outlet></router-outlet>
</div>

我想从 app.component.html 和 profile.component.html 将单个用户放在导航栏中,但我不知道该怎么做。

非常感谢您。

【问题讨论】:

    标签: html node.js angular angular10


    【解决方案1】:

    这个问题对我来说不是很清楚,但我认为这可能会对你有所帮助。 最好创建一个身份验证服务。身份验证服务用于登录和注销,它在用户登录和注销时通知其他组件,并允许访问当前登录的用户。

    RxJS Subjects 和 Observables 用于存储当前用户对象,并在用户登录和退出应用程序时通知其他组件。 Angular 组件可以通过subscribe() 向公共currentUser: Observable 属性通知更改,并在login()logout() 方法中调用this.currentUserSubject.next() 方法时发送通知,将参数传递给每个订阅者。

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { BehaviorSubject, Observable } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    import { User } from '@app/_models';
    
    @Injectable({ providedIn: 'root' })
    export class AuthenticationService {
        private currentUserSubject: BehaviorSubject<User>;
        public currentUser: Observable<User>;
        apiUrl: string;
    
        constructor(private http: HttpClient) {
            this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
            this.currentUser = this.currentUserSubject.asObservable();
        }
    
        public get currentUserValue(): User {
            return this.currentUserSubject.value;
        }
    
        login(username: string, password: string) {
            return this.http.post<any>(`${this.apiUrl}/users/authenticate`, { username, password })
                .pipe(map(user => {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                    this.currentUserSubject.next(user);
                    return user;
                }));
        }
    
        logout() {
            // remove user from local storage to log user out
            localStorage.removeItem('currentUser');
            this.currentUserSubject.next(null);
        }
    }
    

    你可以像这样使用当前用户

    currentUser: User;
    
    constructor(
        private authenticationService: AuthenticationService
    ) {
        this.authenticationService.currentUser.subscribe(x => this.currentUser = x);
    }
    

    如果当前用户未定义,您可以导航到再次登录页面。如果不是,您可以显示当前用户。

    【讨论】:

    • 感谢回复,我会检查并更新帖子
    猜你喜欢
    • 1970-01-01
    • 2020-10-16
    • 2019-06-24
    • 2019-06-08
    • 2019-02-03
    • 2020-06-05
    • 1970-01-01
    • 2015-08-13
    • 2021-02-08
    相关资源
    最近更新 更多