Angular-启动解析器后重构可观察对象

问题描述

我做了一个解析器,我的代码运行得很好。但是我想知道是否有任何方法可以在TS组件中进行refacto,因为我现在从解析器中获取了数据,但是任何时候我尝试擦除一些我认为现在无用的东西时,我的应用就会崩溃。 这是我的解析器:

@Injectable()
export class MatchTableListResolver implements Resolve<MatchTable[]> {
    constructor(private readonly matchTablesService: MatchTablesService
                ) {}

    resolve(route: ActivatedRouteSnapshot,_state: RouterStateSnapshot): Observable<MatchTable[]> {
        console.log("inside resolver")
        return this.matchTablesService.list().map(data => {
            console.log("tata",data); return data});

    }
}

以及我想在我的component.TS文件中重新引用的内容

this.urlWatcher$ = this.route.data.pipe(
        distinctUntilChanged(),withLatestFrom(this.matchTables$),map(([params,newMatchTables]) => {
            this.page = 1;
            this.startIndex = 0;
            this.endindex = 50;

        const matchTableFromParam = newMatchTables.find(m => m.technicalName === params['id']);
        if (matchTableFromParam) {
            this.matchTableSelected = matchTableFromParam;
            this.selectLines(this.startIndex,this.endindex);
        } else {
            if(newMatchTables.length > 0) {
                this.matchTableSelected = newMatchTables[0];
                this.router.navigate(['/configuration/matchtables/' + this.matchTableSelected.technicalName]);
                this.selectLines(this.startIndex,this.endindex);
            }
        }
    })
);

this.matchTableList$ = this.matchTablesService.list().pipe(
    map(matchTables => {
        matchTables = matchTables.sort((a,b) => a.name.toLocaleLowerCase() === b.name.toLocaleLowerCase() ? 0 : a.name.toLocaleLowerCase() < b.name.toLocaleLowerCase() ? -1 : 1);
        this.matchTables$.next(matchTables);
    }),catchError( (error: HttpErrorResponse) => {
        this.loadingError$.next(true);
        return EMPTY;
    })
);

concat(this.matchTableList$,this.urlWatcher$).subscribe();

因为我现在正在使用:

this.listMatchTable = this.route.snapshot.data.listMatchTable;

我不习惯使用解析器,但是我想现在我从解析器接收数据了,我应该能够使事情有所不同(也许摆脱可观察性?),但是我不知道从哪里开始。

解决方法

您可以使用快照字段从路由获取数据和参数

this.id = this.route.snapshot.params['id'];
this.listMatchTable = this.route.snapshot.data.listMatchTable;

然后,您可以在没有可观察对象的情况下实现逻辑

this.page = 1;
this.startIndex = 0;
this.endIndex = 50;

const matchTableFromParam = this.listMatchTable.find(m => m.technicalName === this.id);
 if (matchTableFromParam) {
   this.matchTableSelected = matchTableFromParam;
   this.selectLines(this.startIndex,this.endIndex);
 } else {
   if(newMatchTables.length > 0) {
     this.matchTableSelected = this.listMatchTable[0];
     this.router.navigate(['/configuration/matchtables/' + this.matchTableSelected.technicalName]);
     this.selectLines(this.startIndex,this.endIndex);
   }
 }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...