angular - การดึงคอมโพเนนต์และเส้นทางที่ใช้งานอยู่
ด้วย Angular2 ฉันจะดึงคอมโพเนนต์ที่ใช้งานอยู่ปัจจุบันและเส้นทางได้อย่างไร?
ตัวอย่างเช่น ฉันอาจมีเส้นทางดังต่อไปนี้:
{ path: '', component: HomeComponent },
{ path: 'list', component: ListComponent },
{ path: ':id/', component: CustomComponent }
ถ้าฉันได้เข้าไปที่ https://domain.com/test มีวิธีใดบ้างที่จะรู้ว่าฉันกำลังดู CustomComponent และดึง id/path ซึ่งในกรณีนี้คือ "test"?
ฉันสามารถใช้ window.location.pathname กับ regex เพื่อดึง path ได้ แต่สิ่งนี้ยุ่งยากและยังไม่อนุญาตให้ฉันสามารถดึง component ที่กำลังใช้งานได้อย่างง่ายดาย
คำตอบ #1
ใช่ คุณสามารถตรวจสอบคอมโพเนนต์ที่กำลังทำงานอยู่ปัจจุบันโดยใช้ router snapshot
import { Router,ActivatedRoute } from '@angular/router';
constructor(public route : ActivatedRoute) {
var snapshot = route.snapshot;
console.log(snapshot._routeConfig.component.name); //This will give you the name of current active component
}
หมายเหตุ- snapshot._routeConfig.component.name มันจะแสดงชื่อคอมโพเนนต์ที่กำลังทำงานอยู่ และถ้าคุณต้องการ URL คุณก็สามารถใช้ .url แทนชื่อได้
คำตอบ #2
ใน ActivatedRouteSnapshot คุณสมบัติ component ถูกกำหนดให้เป็นหนึ่งในสิ่งต่อไปนี้
component: Type<any> | string | null;
ดังนั้นคุณจึงไม่สามารถทำ component.name ได้เว้นแต่ว่าคุณได้ตรวจสอบแล้วว่ามี Type<any> นี่เป็นเพราะว่า .name บนสตริงไม่มีอยู่
ตอนนี้ Type<any> จริงๆ แล้วเป็นฟังก์ชันที่สร้างชนิด (ชนิดคอมโพเนนต์ของคุณ) และถูกกำหนดไว้ดังนี้:
export interface Type<T> extends Function {
new (...args: any[]): T;
}
ดังนั้นคุณสามารถทำบางอย่างแบบนี้ ซึ่งจริงๆ แล้วจะคอมไพล์ได้
if (typeof(this.route.snapshot.component) === 'function')
{
// the compiler is 'smart' enough to know that component here must be Type<T>
const name = this.route.snapshot.component.name;
}
วิธีที่ 'สง่างาม' ในการทำคือการใช้ typeguard ของ TypeScript (แม้ว่าพูดตรง ๆ ในกรณีนี้มันจะไม่ให้ประโยชน์มากนักเหนือสิ่งที่ฉันเพิ่งพูดไป)
isComponent(item: Type<any> | string | null): item is Type<any>
{
return typeof item === 'function';
}
แล้วคุณสามารถพูดได้ว่า this.name=isComponent(this.route.snapshot.component) ? this.route.snapshot.component : null.
สำคัญ: component.name ยังคงใช้ได้ใน build แบบ AOT แต่โชคร้ายที่กับ --prod มันจะกลายเป็นบางอย่างที่สุ่มเช่น r
ฉันได้จำเป็นต้องฉีด private element: ElementRef<HTMLElement> แล้วจึงมองหาชื่อแท็ก ซึ่งสิ่งนี้จะยังคงอยู่แม้จะใช้ AOT prod build การทำแบบนี้อาจมีค่าใช้จ่ายด้านประสิทธิภาพ ดังนั้นควรทำการแคชถ้าคุณใช้มันบ่อย
if (element.nativeElement.tagName.startsWith('RR-')){
super.name = element.nativeElement.tagName;
}
