简体   繁体   English

如何在 Angular 10 的 Angular 组件中显示数据?

[英]How can I show data in an Angular component in Angular 10?

I'm starting with Angular 10 and I want to put the current user in the profile.component.html and the navbar in app.component.html.我从 Angular 10 开始,我想将当前用户放在 profile.component.html 中,并将导航栏放在 app.component.html 中。 Here is the code.这是代码。

users.ts用户.ts

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

login.component.ts登录.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 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应用程序组件.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>

I want to put a single user in the navbar from app.component.html and profile.component.html but i don't know how to do it.我想在 app.component.html 和 profile.component.html 的导航栏中放置一个用户,但我不知道该怎么做。

Beforehand thank you very much.事先非常感谢。

The problem is not much clear to me, but I think this may help you.这个问题对我来说不是很清楚,但我认为这可能对你有帮助。 It is better to create an authentication service.最好创建一个身份验证服务。 The authentication service is used to login & log out, it notifies other components when the user logs in & out, and allows access the currently logged in user.身份验证服务用于登录和注销,它在用户登录和注销时通知其他组件,并允许访问当前登录的用户。

RxJS Subjects and Observables are used to store the current user object and notify other components when the user logs in and out of the app. RxJS Subjects 和 Observables 用于存储当前用户对象并在用户登录和退出应用程序时通知其他组件。 Angular components can subscribe() to the public currentUser: Observable property to be notified of changes, and notifications are sent when the this.currentUserSubject.next() method is called in the login() and logout() methods, passing the argument to each subscriber. 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);
    }
}

you can use the current user like this您可以像这样使用当前用户

currentUser: User;

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

if the current user is undefined, you can navigate to again login page.如果当前用户未定义,您可以导航到再次登录页面。 if not you can display the current user.如果没有,您可以显示当前用户。

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

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