【问题标题】:Angular:: error TS2532: Object is possibly 'undefined'Angular:: 错误 TS2532:对象可能是“未定义”
【发布时间】:2021-10-07 11:21:37
【问题描述】:

我正在做 Angular Tour-hero 项目(将 Hero 替换为“用户”)。当我将 Hero(User) 和 Hero-detail(User-detail) 分开时,当我尝试访问详细信息时,它没有显示,更新功能也不起作用。它显示此错误:

错误 TS2532:对象可能是“未定义”。

6

user 对象是,我认为,给出了问题。但是当我尝试完全按照教程添加 MessageService 和所有内容时,它就可以工作了。但是当我删除所有这些时,它给出了这个错误。 提前感谢您的帮助。

用户详细信息.component.html:

<div>
  <h2>{{user.name | uppercase}} Details</h2>
  <div><span>id: </span>{{user.id}}</div>
  <div>
        <label for="user-name">User name: </label>
        <input id="user-name" [(ngModel)]="user.name" placeholder="name">
    </div>
    <button (click)="goBack()">Back</button>
    <button (click)="save()">Save</button>
</div>

user-detail.component.ts:

import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/model/user';
import { UserService } from 'src/app/services/user/user.service';
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.scss']
})
export class UserDetailComponent implements OnInit {
  user?: User

  constructor(
    private userService: UserService,
    private location: Location,
    private route: ActivatedRoute
  ) { }

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

  getUser(): void {
    const id =
     parseInt(this.route.snapshot.paramMap.get('id')!, 1);
    this.userService.getUser(id)
      .subscribe(user => this.user = user);
  }

  goBack(): void {
    this.location.back();
  }

  save():void {
    if(this.user){
      this.userService.updateUser(this.user)
        .subscribe(() => this.goBack())
    }
  }

}

user.service.ts:

import { Injectable } from '@angular/core';
import { User } from 'src/app/model/user';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  
  private usersUrl = 'api/users/';

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json'})
  };

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.usersUrl).pipe(
      catchError(this.handleError<User[]>('getUsers',[]))
    );
  }

  /** GET hero by id. Will 404 if id not found */
  getUser(id: number): Observable<User> {
    const url = `${this.usersUrl}/${id}`;
    return this.http.get<User>(url).pipe(
      catchError(this.handleError<User>(`getUser id=${id}`))
    );
  }

  updateUser(user: User): Observable<any> {
    return this.http.put(this.usersUrl, user, this.httpOptions)
    .pipe(
        catchError(this.handleError<User[]>('getUsers',[]))
    );
  }

  addUser(user: User): Observable<User>{
    return this.http.post<User>(this.usersUrl, user, this.httpOptions)
      .pipe(
        catchError(this.handleError<User>('addUser'))
      )
  }

  deleteUser(id: number): Observable<User>{
    const url = `${this.usersUrl}/${id}`;

    return this.http.delete<User>(url, this.httpOptions).pipe(
      catchError(this.handleError<User>('deleteUser'))
    )
  }

  constructor(private http: HttpClient) { }

  private handleError<T>(operation = 'operation', result?:T){
    return (error: any): Observable<T> => {
      console.error(error);
      return of(result as T);
    }
  }
}

【问题讨论】:

标签: angular angular-routing angular-services angular-ngmodel


【解决方案1】:

我相信这个错误是由于 typescript 版本 2.1 或更高版本,你的代码是完美的!没有任何问题,但是没有初始化的变量减速的方式可能会导致这个错误,

现在如果您知道用户值或者您想使用任何默认值进行初始化,那么请在构造函数中初始化您的用户变量,如下所示

user: User;

constructor() {
  this.user = {
    id: 0,
    name: ''
  };
}

另一个解决方案是利用 'Definite Assignment Assertion' 告诉 typescript 这个变量在运行时会有一个值,如下所示

组件.ts

user!: User;

还可以像下面这样使用 component.html 文件进行更改

<div>
  <h2>{{user?.name! | uppercase}} Details</h2>
  <div><span>id: </span>{{user?.id!}}</div>
  <div>
    <label for="user-name">User name: </label>
    <input id="user-name" [(ngModel)]="user?.name!" placeholder="name">
  </div>
  <button (click)="goBack()">Back</button>
  <button (click)="save()">Save</button>
</div>

【讨论】:

  • 不客气!
  • 还有一件事,我想问。如您所见,这是一个包含用户名的列表。我想根据这些用户名制作一个登录系统。就像使用这些名称一样,可以登录到站点。关于如何做的任何建议?我不想把它作为一个全栈应用程序来做。我使用假 web-api 作为后端。那么我应该将这些名称存储在哪里以及如何检索呢?
  • 你可以使用firebase @OusiBoi
  • 我不想使用 firebase。我只想使用 localStorage
  • 好吧,如果没有实际的服务器,你想创建登录系统,那么你需要创建一些模拟服务,这些服务将离线读取数据,你需要创建一个 JSON 文件,其中包含用户列表在您的项目目录中登录凭据,验证来自该 JSON 文件的身份验证,如果身份验证通过,则在仪表板或主屏幕上路由用户,开始根据您的要求执行其他操作,请注意这不是实际的解决方案,这只是一个想法通过它你可以满足你的期望,
【解决方案2】:

您无需将用户标记为可选

user-detail.component.ts:

import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/model/user';
import { UserService } from 'src/app/services/user/user.service';
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.scss']
})
export class UserDetailComponent implements OnInit {
  user: User

  constructor(
    private userService: UserService,
    private location: Location,
    private route: ActivatedRoute
  ) { }

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

  getUser(): void {
    const id =
     parseInt(this.route.snapshot.paramMap.get('id')!, 1);
    this.userService.getUser(id)
      .subscribe(user => this.user = user);
  }

  goBack(): void {
    this.location.back();
  }

  save():void {
    if(this.user){
      this.userService.updateUser(this.user)
        .subscribe(() => this.goBack())
    }
  }

}

【讨论】:

  • 它给出了这个错误 'error TS2564: Property 'user' has no initializer 并且没有在构造函数中明确分配。 14个用户:用户'
猜你喜欢
  • 2022-01-05
  • 2021-12-29
  • 1970-01-01
  • 2020-12-01
  • 2022-01-20
  • 2021-11-29
  • 2021-12-15
相关资源
最近更新 更多