How to access the *angular 2* components' data

2020-03-01 18:40发布

问题:

I have a DisplayComponent and I'd like to see it's data in the browser's/developer's console. How can I see it?

Example from Angular2 step by step guide:

function DisplayComponent() {
  this.myName = "Alice";
}

How do I see this.myName in the browser's/developer's console?

* Please note that this is a question about Angular 2 and not Angular 1. The suggested solution for AngularJS (Angular 1) doesn't work.

回答1:

Check out this plunker. So basically what you need to do at this moment:

  1. Add test_lib.js to the page
  2. Add ELEMENT_PROBE_BINDINGS to your app bindings.

    import { bootstrap } from 'angular2/angular2'
    import { ELEMENT_PROBE_BINDINGS} from 'angular2/debug'
    import { App } from './app'
    
    bootstrap(App,ELEMENT_PROBE_BINDINGS )
        .catch(err => console.error(err));
    
  3. Use ng.probe method to check the element:

    const app = document.querySelector('my-app');
    const debugElement = ng.probe(app);
    


回答2:

var componentTag = document.querySelector('.component-tag'); var componentDetails = window.ng.probe(kitchenSink); componentDetails.componentInstance

For more details see https://www.pluralsight.com/guides/front-end-javascript/debugging-angular-2-applications#console



回答3:

Did u try simple console command?

console.log(this.myName)

Hope I understand ur question correctly.