Angular2项目日常开发中所遇问题及解决方案记录(三)

1、angular2中监听window.resize?

可以采用@HostListener(),具体的可以去看官方API文档。

@Directive({
 selector: "[d]"
 })
 export class PositioningFromParent implements AfterViewInit {
     private el:HTMLElement
    
    constructor(el: ElementRef) {
    this.el = el.nativeElement
    }
    
    ngAfterViewInit() {
      this.updateLeft();
    }
    
    @HostListener('window:resize') 
    updateLeft() {
      let v = this.el.parentNode.getBoundingClientRect().right
      this.el.style[left] = v + "px"
    }
}

2、在父级Component的styles中包含了子级component的模板样式,子级component模板编译时,找不到对应的样式。

父级component:

@Component({
    selector : 'houses-page',
    templateUrl : 'app/pages/houses/page/houses.page.component.html',
    styleUrls : ['styles/house/list/houseList.css']
})

houseList.css部分样式:

.house_showContent{
    height: 100%;padding-bottom: 0;
    .house_show{
        height: 100%;
        overflow: scroll;
        padding-bottom: 80px;
    }
}

当component模板编译后,查看页面元素:父级houses-page,子级houses-list

Angular2项目日常开发中所遇问题及解决方案记录(三)_第1张图片

但是审查元素发现.housr_show并没有在页面上生效!

Angular2项目日常开发中所遇问题及解决方案记录(三)_第2张图片

最后如果把样式放在index.html主页面上,而不是放在component的styleUrls属性里,.housr_show却是可以找到的:

3、angular2路由的传递及参数接收?

  • url带?

    {
      path : 'home',
      component : CustomComponent
    }
    

html页面:

routerLink="/home" [queryParams]="{destination : destination}"

或者在ts文件内:

this.router.navigate(['/home'],{queryParams : {destination : keyword}});

参数接收:

constructor (private route : ActivatedRoute) {
    this.keywords = this.route.snapshot.queryParams['destination'] || '';
}
  • url不带?

路由配置加参数:

  {
    path : 'home/:destination',
    component : CustomComponent
  }

html页面:

[routerLink]="['/home', destination ]"

或者在ts文件内:

this.router.navigate(['home', destination]);

参数接收:

constructor (private route : ActivatedRoute) {
    this.keywords = this.route.snapshot.params['destination'] || '';
}

try do it !

4、怎样在typescript中引入第三方库?举个例:怎样在typescript中引入toastr。

/// 

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

@Component({
    selector: 'my-app', 
    template: `
      
Display Toastr
` }) export class AppComponent { constructor() { toastr.options = { positionClass: 'toast-bottom-right', } } displayToastr() { toastr.info('message'); } }

上面的toaster.d.ts去这里找吧!

https://github.com/DefinitelyTyped/DefinitelyTyped

5、angularjs里面有同学使用ng-repeat时,好多会写个指令来执行循环结束后的事件,那在angular2里面呢?也可以这样,直接上代码~

先写个isLast指令:

import { Directive, Input, Output, EventEmitter, OnInit} from "@angular/core";

@Directive({
  selector : '[isLast]'
})

export class IsLastDirective implements OnInit{

  @Input() isLast : boolean;
  @Output() lastDone : EventEmitter = new EventEmitter();

  ngOnInit(): void {
    if (this.isLast) {
      this.lastDone.emit(true);
    }
  }
}

那在我们使用*ngFor的时候就可以使用了:

6、在angularjs里面可以使用拦截器(interceptor),来为http请求headers统一处理,比如这样:

module.factory('sessionInjector', ['SessionService', function(SessionService) {
    var sessionInjector = {
        request: function(config) {
            if (!SessionService.isAnonymus) {
                config.headers['x-session-token'] = SessionService.token;
            }
            return config;
        }
    };
    return sessionInjector;
}]);

module.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('sessionInjector');
}]);

那么angular2中呢?
查询了官方API之后,发现BaseRequestOptions这个是可以满足我们的要求的,上码:
第一步:
先创建个class:

import {BaseRequestOptions} from "@angular/http";

export class ArRequestOptions extends BaseRequestOptions {

  private X_Auth_Token : any;

  constructor() {
    super();
    this.X_Auth_Token = localStorage.getItem("xAuthToken");
    this.headers.append('x-auth-token',this.X_Auth_Token);
  }
}

第二步,在app.module.ts里面加入配置:

  providers : [
    {
      provide : RequestOptions,
      useClass : ArRequestOptions
    }
  ]

这样,就可以实现统一全部请求加入x-auth-token的目的。

第三期就到这里吧~下期再见!

你可能感兴趣的:(Angular2项目日常开发中所遇问题及解决方案记录(三))