嗨,我有一个登录组件,所以在我的登录组件.ts文件中,我怎么知道什么时候:
- 此组件从路由器调用,如 https://my-domain/login
- 此组件包含(嵌入(自父组件
谢谢大家
您的问题的答案肯定是使用Component Lifecycle Hook
.
例如,在Login Component
中,您可以使用 ngOnInit(({} 来跟踪它是否被实例化。每当调用登录组件时,也会调用该函数。
constructor(private logger: LoggerService) { }
ngOnInit(){
this.logIt(`onInit`);
}
此外,还有很多生命周期钩子,请选择任何一种适合您的愿望。
这是一个非常不寻常的情况。
一种解决方案是在加载所述登录组件时检查应用程序的路由。
使用此链接了解获取应用程序当前 URL 的不同方法。 就个人而言,我更喜欢这个:
constructor(router: Router) {
const url = router.url;
if(url.indexOf('login') > 0) {
// this is component is loaded from login route
} else {
// this is loaded from parent component
}
}
测试路由器组件的类似乎更有趣:this.route.snapshot.component !== this.constructor;
例:
import {OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
embedded: boolean = false;
constructor(
private route: ActivatedRoute,
){}
ngOnInit() {
this.embedded = this.route.snapshot.component !== this.constructor;
}
}