Ionic 管道改造中的承诺

6tqwzwtp  于 2022-12-08  发布在  Ionic
关注(0)|答案(2)|浏览(142)

我不想用“|异步管道”,因为我不想为每个组件获取数据。我的转换函数如下:

transform(key: string, ...args) {
  this.storage.get("dictionary").then((dict) => {         
   var translated = dict[key] || "noResource";
   console.log("key = "+key + ", value = "+translated);
   return translated; 
  });  
}

我可以得到键和值,但值不呈现。我尝试了ngZone,但不工作。

2ekbmq32

2ekbmq321#

I don't understand why you don't want to use the only "buildin" pipe that matches your case.
says your pipe is :

@Pipe({name: 'mypipe'})
    export class MyPipe implements PipeTransform
    {
        transform(key: string, ...args) {
            // watch out you missed the return statement !!
            -->return<-- this.storage.get("dictionary").then((dict) => {         
            var translated = dict[key] || "noResource";
            console.log("key = "+key + ", value = "+translated);
            return translated; 
        });  
    }

the in your template you could just use

{{ 'mykey' | mypipe | async }}

If you don't want to use async pipe you will be forced to mimic is logic who is already dead simple and bug proof. No gain for you.

62o28rlo

62o28rlo2#

如果您希望管道是异步的,并在以后进行自我更新,我认为唯一的方法是使用WrappedValue
例如,Promise在1s后更新管道。在您的用例中,它的工作方式完全相同。
观看现场演示:https://stackblitz.com/edit/angular-knamur?file=src%2Fapp%2Ftest-async.ts

@Pipe({name: 'testAsync', pure: false})
export class TestAsyncPipe implements PipeTransform {

  private val: number;
  private originalValue: number;

  constructor(private _ref: ChangeDetectorRef) {}

  transform(value: number): any {
    if (value === this.originalValue) {
      return this.val;
    } else {
      new Promise(resolve => {
        setTimeout(() => resolve(value * 2), 1000) ;
      }).then((v: number) => {
        this.val = v + 1;
        this._ref.markForCheck();
      });
    }

    this.originalValue = value;
    this.val = value;

    return WrappedValue.wrap(value);
  }
}

然后在模板中用途:

{{ 42 | testAsync }}

1s后,它将更新模板并显示85

相关问题