developer tip

Angular JavaScript 코드를 디버깅하는 방법

copycodes 2020. 8. 13. 23:33
반응형

Angular JavaScript 코드를 디버깅하는 방법


Angular JavaScript를 사용하여 개념 증명 작업 중입니다.

다른 브라우저 (Firefox 및 Chrome)에서 Angular JavaScript 코드를 디버깅하는 방법은 무엇입니까?


1. 크롬

크롬 에서 AngularJS 디버그의 경우 AngularJS Batarang을 사용할 수 있습니다 . (플러그인에 대한 최근 리뷰에서 AngularJS Batarang이 더 이상 유지되지 않는 것 같습니다. 다양한 버전의 크롬에서 테스트는 작동하지 않습니다)

설명 및 데모 링크는 다음과 같습니다.

Angular JS Batarang 소개

여기에서 크롬 플러그인 다운로드 : AngularJS 디버그 용 크롬 플러그인

이 링크를 참조 할 수도 있습니다 : ng-book : Debugging AngularJS

ng-inspect를 사용하여 각도를 디버깅 할 수도 있습니다.

2. Firefox

들어 파이어 폭스 의 도움으로 방화범 당신은 코드를 디버깅 할 수 있습니다.

이 Firefox 부가 기능 도 사용하십시오 : AngScope : Firefox 용 부가 기능 (AngularJS 팀의 공식 확장이 아님)

3. AngularJS 디버깅 : 링크 확인 : AngularJS 디버깅


IMHO, 가장 실망스러운 경험은 시각적 요소와 관련된 특정 범위의 값을 얻거나 설정하는 것입니다. 내 코드뿐만 아니라 angular.js 자체에서도 많은 중단 점을 수행했지만 때로는 가장 효과적인 방법이 아닙니다. 아래 방법은 매우 강력하지만 실제로 프로덕션 코드에서 사용하는 경우에는 확실히 나쁜 습관으로 간주되므로 현명하게 사용하십시오!

시각적 요소에서 콘솔에서 참조 가져 오기

대부분의 비 IE 브라우저에서는 요소를 마우스 오른쪽 단추로 클릭하고 "요소 검사"를 클릭하여 요소를 선택할 수 있습니다. 또는 예를 들어 Chrome의 요소 탭에서 요소를 클릭 할 수도 있습니다. 가장 최근에 선택한 요소는 $0콘솔의 변수 저장 됩니다.

요소에 연결된 범위 가져 오기

격리 범위를 만드는 지시문이 있는지 여부에 따라 angular.element($0).scope()또는 angular.element($0).isolateScope()( $($0).scope()$가 활성화 된 경우 사용)로 범위를 검색 할 수 있습니다 . 이것은 Batarang의 최신 버전을 사용할 때 얻는 것입니다. 값을 직접 변경하는 경우를 사용 scope.$digest()하여 UI에 변경 사항을 반영해야합니다.

$ eval은 악

디버깅을 위해 반드시 필요한 것은 아닙니다. scope.$eval(expression)표현식에 예상 값이 있는지 신속하게 확인하려는 경우 매우 편리합니다.

범위의 누락 된 프로토 타입 구성원

전자 scope.bla의 차이 scope.$eval('bla')는 원형으로 상속 된 값을 고려하지 않습니다. 아래 스 니펫을 사용하여 전체 그림을 얻으십시오 (값을 직접 변경할 수는 없지만 $eval어쨌든 사용할 수 있습니다 !).

scopeCopy = function (scope) {
    var a = {}; 
    for (x in scope){ 
        if (scope.hasOwnProperty(x) && 
            x.substring(0,1) !== '$' && 
            x !== 'this') {
            a[x] = angular.copy(scope[x])
        }
    }
    return a
};

scopeEval = function (scope) {
    if (scope.$parent === null) {
        return hoho(scope)
    } else {
        return angular.extend({}, haha(scope.$parent), hoho(scope))
    }
};

와 함께 사용하십시오 scopeEval($($0).scope()).

내 컨트롤러는 어디에 있습니까?

ngModel지시문을 작성할 때 값을 모니터링하고 싶을 때가 있습니다 . 사용 $($0).controller('ngModel')당신은 확인 얻을 것이다 $formatters, $parsers, $modelValue, $viewValue $render모든 것을.


사용할 수있는 $ log도 있습니다! 그것은 당신이 원하는 방식으로 콘솔을 사용합니다!

콘솔에 정상적으로 표시되는 방식으로 오류 / 경고 / 정보 표시!

이것을 사용> 문서


Despite the question is answered, it could be interesting to take a look at ng-inspector


Try ng-inspector. Download the add-on for Firefox from the website http://ng-inspector.org/. It is not available on the Firefox add on menu.

http://ng-inspector.org/ - website

http://ng-inspector.org/ng-inspector.xpi - Firefox Add-on


Unfortunately most of add-ons and browser extensions are just showing the values to you but they don't let you to edit scope variables or run angular functions. If you wanna change the $scope variables in browser console (in all browsers) then you can use jquery. If you load jQuery before AngularJS, angular.element can be passed a jQuery selector. So you could inspect the scope of a controller with

angular.element('[ng-controller="name of your controller"]').scope()

Example: You need to change value of $scope variable and see the result in the browser then just type in the browser console:

angular.element('[ng-controller="mycontroller"]').scope().var1 = "New Value";
angular.element('[ng-controller="mycontroller"]').scope().$apply();

You can see the changes in your browser immediately. The reason we used $apply() is: any scope variable updated from outside angular context won't update it binding, You need to run digest cycle after updating values of scope using scope.$apply() .

For observing a $scope variable value, you just need to call that variable.

Example: You wanna see the value of $scope.var1 in the web console in Chrome or Firefox just type:

angular.element('[ng-controller="mycontroller"]').scope().var1;

The result will be shown in the console immediately.


Add call to debugger where you intend to use it.

someFunction(){
  debugger;
}

In the console tab of your browser's web developer tools, issue angular.reloadWithDebugInfo();

Visit or reload the page you intend to debug and see the debugger appear in your browser.


var rootEle = document.querySelector("html");
var ele = angular.element(rootEle); 

scope() We can fetch the $scope from the element (or its parent) by using the scope() method on the element:

var scope = ele.scope();

injector()

var injector = ele.injector();

With this injector, we can then then instantiate any Angular object inside of our app, such as services, other controllers, or any other object


You can add 'debugger' in your code and reload the app, which puts the breakpoint there and you can 'step over' , or run.

var service = {
user_id: null,
getCurrentUser: function() {
  debugger; // Set the debugger inside 
            // this function
  return service.user_id;
}

You can debug using browsers built in developer tools.

  1. open developer tools in browser and go to source tab.

  2. open the file do you want to debug using Ctrl+P and search file name

  3. add break point on a line ny clicking on left side of the code.

  4. refresh the page.

There are lot of plugin available for debugging you can refer for using chrome plugin Debug Angular Application using "Debugger for chrome" plugin


For Visual Studio Code (Not Visual Studio) do Ctrl+Shift+P

Type Debugger for Chrome in the search bar, install it and enable it.

In your launch.json file add this config :

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Launch localhost with sourcemaps",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost/mypage.html",
            "webRoot": "${workspaceRoot}/app/files",
            "sourceMaps": true
        },
        {
            "name": "Launch index.html (without sourcemaps)",
            "type": "chrome",
            "request": "launch",
            "file": "${workspaceRoot}/index.html"
        },
    ]
}

You must launch Chrome with remote debugging enabled in order for the extension to attach to it.

  • Windows

Right click the Chrome shortcut, and select properties In the "target" field, append --remote-debugging-port=9222 Or in a command prompt, execute /chrome.exe --remote-debugging-port=9222

  • OS X

In a terminal, execute /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222

  • Linux

In a terminal, launch google-chrome --remote-debugging-port=9222

Find More ===>


Since the add-ons don't work anymore, the most helpful set of tools I've found is using Visual Studio/IE because you can set breakpoints in your JS and inspect your data that way. Of course Chrome and Firefox have much better dev tools in general. Also, good ol' console.log() has been super helpful!


Maybe you can use Angular Augury A Google Chrome Dev Tools extension for debugging Angular 2 and above applications.

참고URL : https://stackoverflow.com/questions/18782069/how-to-debug-angular-javascript-code

반응형