Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Angular:访问一个";中声明的this.id;OnInit“;功能 更新1_Javascript_Angular_Class_Parameters_Angular Ui Router - Fatal编程技术网

Javascript Angular:访问一个";中声明的this.id;OnInit“;功能 更新1

Javascript Angular:访问一个";中声明的this.id;OnInit“;功能 更新1,javascript,angular,class,parameters,angular-ui-router,Javascript,Angular,Class,Parameters,Angular Ui Router,在阅读了Alexanders的建议之后,我更新了代码,没有收到任何错误回复。但是Angular不再向服务器发出请求,这让我很好奇。而且页面标题也不会更新 appointmentDetail.component.html 任命详情.component.ts 如您所见,我想从路由器参数中获取该参数id,并将其传递到API调用中,该调用将执行角度HTTP请求。希望我是对的,哈哈 原始问题 目前,我遇到了一个棘手的问题。问题是,我想读取参数,这些参数是由ActivatedRouter和AngularO

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

appointmentDetail.component.html 任命详情.component.ts 如您所见,我想从路由器参数中获取该参数
id
,并将其传递到API调用中,该调用将执行角度HTTP请求。希望我是对的,哈哈


原始问题 目前,我遇到了一个棘手的问题。问题是,我想读取参数,这些参数是由
ActivatedRouter
和Angular
OnInit
函数提供给我的。我订阅这些参数并将它们记录在控制台中。在这里之前,一切都很顺利。但是我想从我的
OnInit
函数外部访问“
this.id
”,因此我可以在pageTitle上使用它


但是,此.id未定义。因此,页面标题没有定义

源代码:

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);
      });
  }
}
从'@angular/core'导入{Component,OnInit,OnDestroy,Injectable};
从'@angular/router'导入{ActivatedRoute};
从“@angular/platform browser”导入{Title};
从“/../../api.service”导入{APIService};
@组成部分({
选择器:“应用程序约会详细信息”,
templateUrl:“./appointment details.component.html”,
样式URL:['./约会详细信息.component.scss']
})
@可注射()
导出类AppointmentDetails组件实现OnInit、OnDestroy{
专用路由sub:any;
id:任何;
私人任命详细信息:数组=[];
建造师(
专用路由:激活的路由,
私人头衔:头衔,
私人apiService:apiService
) {}
pageTitle='Term'+this.id;
恩戈尼尼特(){
this.title.setTitle(this.pageTitle);
这是getData();
this.routeSub=this.route.params.subscribe(params=>{
控制台日志(params);
this.id=params['id'];
});
}
恩贡德斯特罗(){
this.routeSub.unsubscribe();
}
公共获取数据(){
这是我们的服务
.getAppointmentDetailsById(this.id)
.subscribe((数据:数组)=>{
this.appointmentDetail=数据;
控制台日志(数据);
});
}
}

这里的问题实际上归结为路由参数和可观察流的异步可用性。在解决所有实际问题之前,您无法使用该值。您可以根据官方文档使用RxJS操作符,如
switchMap
tap
,以确保路由参数
id
在使用前可用<代码>点击可用于引入副作用,例如从路由参数和/或设置标题设置class
id
属性。您甚至可以创建一个可观察的类属性,并利用Angular Async管道来避免订阅和取消订阅以显示数据

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;
    });
    */
  }

}
从'@angular/core'导入{Component,OnInit};
从'@angular/router'导入{ActivatedRoute};
从“@angular/platform browser”导入{Title};
从“/../../api.service”导入{APIService,MyFancyInterface};
从“rxjs”导入{Observable};
从“rxjs/operators”导入{switchMap,tap};
@组成部分({
选择器:“应用程序约会详细信息”,
templateUrl:“./appointment details.component.html”,
样式URL:['./约会详细信息.component.scss']
})
导出类AppointmentDetails组件实现OnInit{
id:任何;
任命详情$:可见;
任命详情:MyFancyInterface;
pageTitle='某些默认标题可能';
建造师(
专用路由:激活的路由,
私人头衔:头衔,
私人apiService:apiService
) {}
恩戈尼尼特(){
this.appointmentDetail$=this.route.paramMap.pipe(
轻触((参数:参数映射)=>{
this.id=params.get('id')
//或者this.id=+params.get('id');强制键入number
this.pageTitle='term'+this.id;
this.title.setTitle(this.pageTitle);
}),
switchMap(()=>this.apiService.getAppointmentDetailsById(this.id))
);
/*或
this.route.paramMap.pipe(
轻触((参数:参数映射)=>{
this.id=params.get('id')
//或者this.id=+params.get('id');强制键入number
this.pageTitle='term'+this.id;
this.title.setTitle(this.pageTitle);
}),
switchMap(()=>this.apiService.getAppointmentDetailsById(this.id))
).subscribe((数据:MyFancyInterface)=>{
this.appointmentDetail=数据;
});
*/
}
}
模板:

<div>{{(appointmentDetail | async)?.id}}</div>
{{(任命细节|异步)?.id}
我建议创建一个接口来表示您的数据模型,并键入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}`);
  }
  ...
}
从'rxjs'导入{Observable};
//也许把这个放到另一个文件里
导出接口MyFancyInterface{
id:编号;
someProperty:字符串;
...
}
出口级服务{
...
GetAppointDetailsById(id):可观察{
返回this.httpClient.get(`${this.API_URL}/appoints/${id}`);
}
...
}
如果确实需要,您可以像现在一样为route params保存observable,并根据需要在类的各个部分中订阅,但通过这种演示方式,您几乎完全知道route param
id
将可供使用,并且可以显式设置需要设置的内容

我还将删除
@Injectable()
,因为这里没有理由使用
@Component()
装饰器

注意*本例中的异步管道操作符确保执行Http调用。否则需要一个subscribe()(搜索不执行的http以查看类似问题)

希望这有帮助

而不是

id:any

你可以试着用吸气剂,就像这样

public get id(): any {
  this.route.params.subscribe(params => {
    return params['id'];
   }
}
在模板中,只需

{{ id }}

那么问题到底是什么呢?您是否无法使用字符串interpo在DOM上查看
id
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}`);
  }
  ...
}
public get id(): any {
  this.route.params.subscribe(params => {
    return params['id'];
   }
}
{{ id }}