在解决Angular 7上非常慢的ng服务问题时,以下是一些可能的解决方法和代码示例:
ChangeDetectionStrategy.OnPush
策略,只在输入属性发生变化时才进行变更检测。trackBy
函数来跟踪*ngFor
循环中的项目,以减少不必要的DOM操作。@Component({
selector: 'app-my-component',
templateUrl: 'my-component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
@Input() data: any[];
trackByFn(index: number, item: any): number {
return item.id; // 使用唯一标识符来跟踪项目
}
}
const routes: Routes = [
{ path: 'lazy', loadChildren: './lazy.module#LazyModule' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
@Component({
selector: 'app-my-component',
templateUrl: 'my-component.html'
})
export class MyComponent {
@ViewChild(CdkVirtualScrollViewport) viewport: CdkVirtualScrollViewport;
items: any[] = [];
constructor(private dataService: DataService) {
this.dataService.getData().subscribe(data => {
this.items = data;
this.viewport.scrollToIndex(0); // 滚动到顶部
});
}
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService {
private cache: any[] = [];
constructor(private http: HttpClient) { }
getData(): Observable {
if (this.cache.length) {
return Observable.of(this.cache); // 返回缓存的数据
} else {
return this.http.get('api/data').pipe(
map(data => {
this.cache = data; // 缓存数据
return data;
})
);
}
}
}
以上是一些解决Angular 7上非常慢的ng服务问题的方法和代码示例。根据具体情况选择适合您项目的解决方案。