javascript - 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 请求。希望我是对的,哈哈。
原始问题
目前,我遇到了一个令人讨厌的问题。问题是,我想阅读由ActivatedRouter
AngularOnInit
函数提供给我的参数。我订阅了它们的参数并将它们记录在控制台中。到这里为止,一切正常。但我想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);
});
}
}
解决方案
这里的问题实际上归结为路由参数和可观察流的异步可用性。在它为所有实际目的解决之前,您根本无法使用该值。您可以使用 RxJS 运算符,例如switchMap
并tap
符合官方路由和导航文档,以确保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 未执行以查看类似问题)
希望这会有所帮助!
推荐阅读
- json - 使用 REST API 更新测试用例结果
- java - Activity 等于 Context 吗?
- mysql-workbench - 错误代码:1054。“字段列表”中的未知列“Cedula”
- swift - 快速反转.label
- html - asp.net core 将模型传递给布局
- c++ - 使用 Poco Library C++ (Gmail) 发送电子邮件
- javascript - Mongoose .populate() 或 .find() 哪个更快
- python - 多核处理器上的 QueryPerformanceCounter 不一致:一个已经消失的问题?
- python - 如何将相同的队列放入不同的多处理文件中?
- python - 通过子进程启动mitmproxy---避免输出和tty检测