浅记一下:angular一些杂七杂八的东东

60 阅读1分钟

动态class的几种方法

<span [class.className1]="判断条件" [class.className2]="判断条件2"></span>
<span [ngClass]="{className: 判断条件1, className2: 判断条件2}"></span>

使用subject实现组件之间传参 => 这里可以再看下不同的subject有什么不同效果(replaySubject,behaviorSubject等)

1.建立一个通用的service

import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs/index';

@Injectable()

export class TemplateCommonService {

  public list$: Observable<IVale>; // 监听list
  private _listSub: Subject<any> = new Subject<any>();

  constructor() {
    this.list$ = this._listSub.asObservable(); //如果有改变的话则会传递消息
  }

  public listStatusChange(value: any): void {
    this._listSub.next(value);
  }
}

2.发送事件

this._templateCommonService.listStatusChange('这里是要发送的值')

3.接收事件

(1)constructor里接收事件
this._subs = this._templateCommonService.list$.subscribe((item) => {
   this._listStatusChange(item);
});
(2)在ngOnDestroy上记得要销毁
this._subs.unsubscribe();

接口复用(同一个接口在不同地方使用不会重复调接口 比如不会变化的下拉菜单)

public cacheList$: Observable<string[]>;

// 这里调用getList()时只会调用一次接口
public getList(): Observable<string[]> {
    this.cacheList$ = this.cacheList$ || this._http.get('这里是接口地址')
                      .pipe(shareReplay());
    return this.cacheList$;
}