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
}
};