async 高級技巧
<div *ngIf="obs|async as obs;else loading">{{obs}}</div>
<ng-template #loading>loading.....</ng-template>
obs = of(1).pipe(delay(1000));
升級版
@Pipe({
name: 'withLoading',
})
export class WithLoadingPipe implements PipeTransform {
transform(val) {
return isObservable(val)
? val.pipe(
map((value: any) => ({ loading: false, value })),
startWith({ loading: true }),
catchError(error => of({ loading: false, error }))
)
: val;
}
}
<div *ngIf="obs$ | withLoading | async as obs">
<ng-template [ngIf]="obs.value">Value: {{ obs.value }}</ng-template>
<ng-template [ngIf]="obs.error">Error {{ obs.error }}</ng-template>
<ng-template [ngIf]="obs.loading">Loading...</ng-template>
</div>
distinctUntilChanged
只有當前值與之前最后一個值不同時才發出
from([1,1,1,2,2,3,4,4]).pipe( distinctUntilChanged() ).subscribe(val=>{ console.log(val); }) //1,2,3,4
crypto-js 打包出現報錯
在package.json
"browser":{
"crypto":false
}
修改<title></title>
標簽的文字
export class OriginalComponent implements OnInit {
constructor(private title:Title) { }
ngOnInit() {
this.title.setTitle('小帥哥')
}
}
覆蓋{{}}
改成((xxx))
@Component({
selector: 'app-original',
templateUrl: './original.component.html',
styleUrls: ['./original.component.less'],
interpolation: ['((', '))']
})
Location
import {Location} from '@angular/common';
constructor(private location:Location) {}
// 返回標准化的url路徑
console.log(this.location.path());
// 對指定的路徑進行標准化,並和當前的標准化路徑進行比較。
// 參數
// path string 指定url路徑
// query string 查詢的參數
console.log(this.location.isCurrentPathEqualTo('/rxjs'));
// 歷史堆棧中追加一個新條目。
this.location.go()
操作DOM
<canvas id="canvas"></canvas>
import {DOCUMENT} from '@angular/common';
export class OriginalComponent implements OnInit, AfterViewInit {
constructor(private title: Title, private location: Location, @Inject(DOCUMENT) private canvas: Document) {
}
ngOnInit() {
}
ngAfterViewInit(): void {
console.log(this.canvas.getElementById('canvas'));
}
}
懶加載的預加載策約(angular8)
預加載策略
NoPreloading
-不預加載(默認)PreloadAllModules
-預加載所有延遲加載的模塊。在app-routing.module.ts
@NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: NoPreloading }) ], exports: [RouterModule] }) export class AppRoutingModule { }
自定義預加載
在需要預加載的模塊,給個標識
{ path: 'module-8', loadChildren: () => import('./lazymodule8/lazymodule8.module').then(m => m.Lazymodule8Module), data: { preload: true } // 標識 }
開啟一個服務
在preload函數內部,我們檢查preload標志是否設置為true,然后返回loader函數,否則我們返回null
export class MyPreloadingStrategyService implements PreloadingStrategy { preload(route: Route, load: () => Observable<any>): Observable<any> { if (route.data && route.data['preload']) { return load(); } else { return of(null); } } }
最后我們把預加載服務設置為預加載策略
@NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: MyPreloadingStrategyService //我們的預加載服務 }) ], exports: [RouterModule] }) export class AppRoutingModule {}
集中訂閱取消
export class AppComponent implements OnInit, OnDestroy {
subscription1$: Subscription
subscription2$: Subscription
subscriptions: Subscription[] = []
ngOnInit () {
var observable1$ = Rx.Observable.interval(1000);
var observable2$ = Rx.Observable.interval(400);
this.subscription1$ = observable.subscribe(x => console.log("From interval 1000" x));
this.subscription2$ = observable.subscribe(x => console.log("From interval 400" x));
this.subscriptions.push(this.subscription1$)
this.subscriptions.push(this.subscription2$)
}
ngOnDestroy() {
this.subscriptions.forEach((subscription) => subscription.unsubscribe())
}
}
修改可以以add
方法進行
export class AppComponent implements OnInit, OnDestroy {
subscription: Subscription=new Subscription();
ngOnInit () {
var observable1$ = Rx.Observable.interval(1000);
var observable2$ = Rx.Observable.interval(400);
var subscription1$ = observable.subscribe(x => console.log("From interval 1000" x));
var subscription2$ = observable.subscribe(x => console.log("From interval 400" x));
this.subscription.add(subscription1$)
this.subscription.add(subscription2$)
}
ngOnDestroy() {
this.subscription.unsubscribe()
}
}
async 給一個
Observable
或Promise
返回一個最新值銷毀組件后,
async
管道將自動取消訂閱,已避免內存泄露a=interval(1000) {{a | async}}
takeUntil
export class AppComponent implements OnInit, OnDestroy {
notifier = new Subject()
ngOnInit () {
var observable$ = Rx.Observable.interval(1000);
observable$.pipe(takeUntil(this.notifier))
.subscribe(x => console.log(x));
}
ngOnDestroy() {// 取消訂閱
this.notifier.next()
this.notifier.complete()
}
}
使用mack
安裝 @delon/mock
依賴包:
yarn add @delon/mock -D
在根模塊 AppModule
導入 Mock 規則數據和 DelonMockModule
;
import { DelonMockModule } from '@delon/mock';
import * as MOCKDATA from '../../_mock';
// 只對開發環境有效
import { environment } from '../environments/environment';
const MOCKMODULE = !environment.production ? [ DelonMockModule.forRoot({ data: MOCKDATA }) ] : [];
@NgModule({
imports: [
...MOCKMODULE
]
})
新建一個_mock 文件夾
index.ts
export * from './_api';
_api.ts
export const CHART = {
/** 菜單欄接口 */
// 獲取平台菜單
'GET /isop/guard/': {
data: false
}
};