TypeScript(Angular)中的执行流程

时间:2019-02-02 15:12:07

标签: angular typescript

我正在尝试学习Angular中的描述符。我正在尝试这段代码,只是为了了解描述符如何操纵原始方法。但是我可以看到@squareLog函数的“ console.log()”语句首先被执行,其余代码按顺序执行。我是Typescript和Angular的100%菜鸟。输出正确吗?这是应该从此代码中获得的期望吗?如果没有,那我是不是搞砸了?

import { Component } from '@angular/core';

function log(target, name, descriptor){
  //store the original function in a variable
  const original = descriptor.value;
  //do some manipulation with descriptor.value
  descriptor.value = function(){
    console.log("This function is with LOG as the descriptor");
  }
  //return the descriptor
  return descriptor;
}

function squareLog (target, name, descriptor){
  console.log("This function is with SQUARELOG as descriptor");
  const original = descriptor.value;
  descriptor.value = function(...args){
    console.log("Arguments ", args, "were passed in this function");
    const result = original.apply(this, args);
    console.log("The result of the function is ", result);
    return result;
  }
  return descriptor;
}

function classLog(className){
  console.log(className);
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

@classLog
export class AppComponent {
  title: string = 'Demonstration of decriptors';

constructor(){
  this.aSimpleMethod();
  console.log("This statement was generated by constructor: ", this.returnSquare(5));
}
  @log
  aSimpleMethod(){
    console.log("Learning about descriptors");
  }

  @squareLog
  returnSquare(a){
    return a*a;
  }
}

实际输出:- enter image description here

1 个答案:

答案 0 :(得分:1)

function f() {
    console.log("f(): evaluated");
    return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log("f(): called");
    }
}

function g() {
    console.log("g(): evaluated");
    return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log("g(): called");
    }
}

class C {
    @f()
    @g()
    method() {}
}