【问题标题】:Angular2 - Show component name and its html template path in DOMAngular2 - 在 DOM 中显示组件名称及其 html 模板路径
【发布时间】:2018-09-28 11:16:31
【问题描述】:

我曾想过在 angular2 应用程序中使用调试器组件,类似于 magento 电子商务功能中的“显示模板路径”。

我想通过触发快捷键在DOM本身中显示左侧的模板路径和红色条右侧的组件名称。这可以帮助开发人员调试大型应用程序。

请告诉我,实现此调试组件的最佳方式可能是什么。该组件应显示从该页面中使用的组件呈现的相应 DOM 的每个组件级别信息。

提前致谢。

【问题讨论】:

    标签: javascript html typescript angular2-template angular2-forms


    【解决方案1】:

    基于 cmets 的更新:

    使用反射包here

    在所有组件中导入它后,使用 Reflect.getMetadata('annotations', ComponentClass) 方法。

    您可以从中提取您的模板URL。

    可以使用activatedRoute接口:Here

    它有当前路由的 URL 以及被激活的组件。

    创建一个名为 DebuggerService 的服务,并在其中包含一个名为 routeMap 的属性,并在 app.module 中提供它。在每个组件上导入并注入此服务。

    所以现在在每个组件的 onInit 或 Constructor 中,你可以这样做:

    @Component({...})
    class MyComponent {
      constructor(private router: Router, debugger: DebuggerService) {
        this.debugger.routeMap += (this.router.url + '' + this.router.routeConfig.component.name)
      }
    }
    

    您基本上所做的是将服务内激活的每条路由连接起来。该值将存储在整个应用程序中,因为它在 app.module 中全局提供。

    您现在可以在 debuggerComponent 中使用 debuggerService 的此属性并打印出所有路由。

    希望这是有道理的。

    【讨论】:

    • 我正在使用模板 url 作为 'templateUrl: 'app/test/test-info.component.html'... 我无法从 (this.route.url.地图(segments => segments.join('')) + ' ' + this.route.component)。请指教
    • 更新我的答案
    • 更新了我的答案:)
    • 这很好,但我无法获取模板 url 路径。我想显示完整的路径 app/test/test-info.component.html。我们如何得到它?
    • 我尝试使用 this.router.url。但是在控制台中,[object Object] componentName....我只需要 templateUrl 来显示
    猜你喜欢
    • 2018-11-09
    • 2020-12-29
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多