首页 > 解决方案 > Angular:访问在“OnInit”函数中声明的 this.id

问题描述

更新 1

在阅读了 Alexanders 的建议后,我更新了代码并且没有收到任何错误。但是 Angular 不再向服务器发出请求,这让我很好奇。而且pageTitle也不更新。

约会Detail.component.html

{{appointmentDetail.time}}

约会Detail.component.ts

import { Component, OnInit, OnDestroy, Injectable } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { APIService } from './../../../api.service';
import { Observable } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';

@Component({
  selector: 'app-appointmentdetail',
  templateUrl: './appointmentDetail.component.html',
  styleUrls: ['./appointmentDetail.component.scss']
})
export class AppointmentDetailComponent implements OnInit {
  id: any;
  appointmentDetail$: Observable<Object>; // I'd really create an interface for appointment or whatever instead of  object or any
  pageTitle = 'Some Default Title Maybe';

  constructor(
    private route: ActivatedRoute,
    private title: Title,
    private apiService: APIService
  ) {}

  ngOnInit() {
    this.appointmentDetail$ = this.route.paramMap.pipe(
      tap((params: ParamMap) => {
        this.id = params.get('id');
        // Or this.id = +params.get('id'); to coerce to number maybe
        this.pageTitle = 'Termin' + this.id;
        this.title.setTitle(this.pageTitle);
      }),
      switchMap(() => this.apiService.getAppointmentDetailsById(this.id))
    );
  }
  public getData() {
    this.apiService
      .getAppointmentDetailsById(this.id)
      .subscribe((data: Observable<Object>) => {
        this.appointmentDetail$ = data;
        console.log(data);
      });
  }
}

api.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class APIService {
  API_URL = 'http://localhost:5000';
  constructor(private httpClient: HttpClient) {}
  getAppointments() {
    return this.httpClient.get(`${this.API_URL}/appointments/`);
  }
  getAppointmentDetailsById(id) {
    return this.httpClient.get(`${this.API_URL}/appointments/${id}`);
  }
  getAppointmentsByUser(email) {
    return this.httpClient.get(`${this.API_URL}/user/${email}/appointments`);
  }
  getCertificatesByUser(email) {
    return this.httpClient.get(`${this.API_URL}/user/${email}/certificates`);
  }
}

如您所见,我想id从路由器参数中获取该参数并将其传递到我的 API 调用中,这将执行 Angular HTTP 请求。希望我是对的,哈哈。


原始问题

目前,我遇到了一个令人讨厌的问题。问题是,我想阅读由ActivatedRouterAngularOnInit函数提供给我的参数。我订阅了它们的参数并将它们记录在控制台中。到这里为止,一切正常。但我想this.id从我的函数外部访问“” OnInit,所以我可以在 pageTitle 上使用它。

但是,this.id 是未定义的。所以页面标题是Termineundefined。

源代码:

import { Component, OnInit, OnDestroy, Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { APIService } from './../../api.service';

@Component({
  selector: 'app-appointment-details',
  templateUrl: './appointment-details.component.html',
  styleUrls: ['./appointment-details.component.scss']
})
@Injectable()
export class AppointmentDetailsComponent implements OnInit, OnDestroy {
  private routeSub: any;
  id: any;
  private appointmentDetail: Array<object> = [];
  constructor(
    private route: ActivatedRoute,
    private title: Title,
    private apiService: APIService
  ) {}

  pageTitle = 'Termin' + this.id;

  ngOnInit() {
    this.title.setTitle(this.pageTitle);
    this.getData();

    this.routeSub = this.route.params.subscribe(params => {
      console.log(params);
      this.id = params['id'];
    });
  }

  ngOnDestroy() {
    this.routeSub.unsubscribe();
  }

  public getData() {
    this.apiService
      .getAppointmentDetailsById(this.id)
      .subscribe((data: Array<object>) => {
        this.appointmentDetail = data;
        console.log(data);
      });
  }
}

标签: javascriptangularclassparametersangular-ui-router

解决方案


这里的问题实际上归结为路由参数和可观察流的异步可用性。在它为所有实际目的解决之前,您根本无法使用该值。您可以使用 RxJS 运算符,例如switchMaptap符合官方路由和导航文档,以确保id在使用前路由参数可用。tap可用于引入副作用,例如id从路由参数设置类属性和/或设置标题。您甚至可以创建一个类属性Observable<YourObject[]>并利用 Angular Async Pipe 来避免订阅和取消订阅来显示数据。

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { APIService, MyFancyInterface } from './../../api.service';
import { Observable } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';

@Component({
  selector: 'app-appointment-details',
  templateUrl: './appointment-details.component.html',
  styleUrls: ['./appointment-details.component.scss']
})
export class AppointmentDetailsComponent implements OnInit {
  id: any;
  appointmentDetail$: Observable<MyFancyInterface>;
  appointmentDetail: MyFancyInterface;
  pageTitle = 'Some Default Title Maybe';

  constructor(
    private route: ActivatedRoute,
    private title: Title,
    private apiService: APIService
  ) {}

  ngOnInit() {
    this.appointmentDetail$ = this.route.paramMap.pipe(
      tap((params: ParamMap) => {
        this.id = params.get('id')
        // Or this.id = +params.get('id'); to coerce to type number maybe
        this.pageTitle = 'Termin' + this.id;
        this.title.setTitle(this.pageTitle);
      }),
      switchMap(() => this.apiService.getAppointmentDetailsById(this.id))
    );

    /* Or
    this.route.paramMap.pipe(
      tap((params: ParamMap) => {
        this.id = params.get('id')
        // Or this.id = +params.get('id'); to coerce to type number maybe
        this.pageTitle = 'Termin' + this.id;
        this.title.setTitle(this.pageTitle);
      }),
      switchMap(() => this.apiService.getAppointmentDetailsById(this.id))
    ).subscribe((data: MyFancyInterface) => {
      this.appointmentDetail = data;
    });
    */
  }

}

模板:

<div>{{(appointmentDetail | async)?.id}}</div>

我建议创建一个接口来表示您的数据模型并输入您的 api 服务方法的返回值:

import { Observable } from 'rxjs';

// maybe put this into another file
export interface MyFancyInterface {
  id: number;
  someProperty: string;
  ...
}

export class APIService {
  ...
  getAppointmentDetailsById(id): Observable<MyFancyInterface> {
    return this.httpClient.get<MyFancyInterface>(`${this.API_URL}/appointments/${id}`);
  }
  ...
}

如果你真的需要,你可以像现在一样为路由参数保存 observable 并根据需要在类的各个部分订阅,但是这种演示方式你几乎绝对知道路由参数id将可用并且可以显式设置你需要设置的东西。

我也会删除@Injectable(),因为没有理由将它与@Component()装饰器一起放在此处。

注意*此示例中的异步管道运算符确保执行 Http 调用。否则需要 subscribe() (搜索 Angular http 未执行以查看类似问题)

希望这会有所帮助!


推荐阅读