如何在angular 2中实现aop [英] how to implement aop in angular 2

查看:34
本文介绍了如何在angular 2中实现aop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 2 的新手,但我在 Angular 1.x 方面有很好的经验.

I am new in Angular 2 but I have good experience in Angular 1.x.

我收到错误:找不到模块aspect.js/dist/lib/aspect"

I am getting error: Cannot find module 'aspect.js/dist/lib/aspect'

下面是我的代码:

logging.aspect.ts

logging.aspect.ts

import {Injectable} from '@angular/core';
import {beforeMethod, Metadata} from 'aspect.js/dist/lib/aspect';
@Injectable()
export class LogAspect {

  @beforeMethod({
    classNamePattern: /(Matter|Customer)Service/,
    methodNamePattern: /^(get)/
  })
  invokeBeforeMethod(meta: Metadata) {
    console.log(`Inside of the logger.
      Called ${meta.className}.${meta.method.name}
      with args: ${meta.method.args.join(', ')}.`
    );
  }
}

aspect 定义了一个通知,该通知应用于所有以 get 开头的方法调用,这些方法调用在名称中包含正则表达式模式 (Matter|Customer)Service 的类中.通知可用的元数据可能包含实际的方法和类名称以及方法调用参数

aspect defines an advice which is applied to all method calls starting with get within classes containing the regex-pattern (Matter|Customer)Service in their name. The Metadata available to the advice may contain the actual method- and class names along with the method-call parameters

invoice.service.ts

invoice.service.ts

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
import {Wove} from 'aspect.js/dist/lib/aspect';
import {Matter} from './Matter.model';
@Injectable()
@Wove()
export class MatterService{
  private url: string;
  constructor(private http: Http) {
    this.url = '/data/matters/data.json';
  }
  get(): Observable<Matter[]> {
    return this.http.get(this.url)
      .map(
        (response) => <Matter[]>response.json()
      );
  }
}

请提出在 angular2 中实现 AOP 的任何其他方法

And please suggest any other way to implement AOP in angular2

推荐答案

你试过 kaop-ts?我发现它更直观,并且在公司项目中对我有用

Have you tried kaop-ts? I find it more intuitive and it is working for me on a company project

// LogAspect.ts    
export class LogAspect {
  static log(meta) {
    console.log('Called: ', meta.target)
    console.log('Args: ', meta.args)
  }
}

// YourService.ts
import { Injectable } from '@angular/core'
import { beforeMethod } from 'kaop-ts'
import { LogAspect } from './LogAspect'

@Injectable()
export class YourService {
  @beforeMethod(LogAspect.log) 
  get() {
    // ....
  }
}

这篇关于如何在angular 2中实现aop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆