gpt4 book ai didi

javascript - Promise then 函数中的 Angular 4 持久存储使用情况

转载 作者:行者123 更新时间:2023-12-03 03:46:41 24 4
gpt4 key购买 nike

尝试在 Promise then 函数中使用 Angular 持久性,但总是显示未定义

import { Component, OnInit, Injectable } from '@angular/core';

import {Router} from "@angular/router";
import {PersistenceService, StorageType} from "angular-persistence";

export class ProcessingComponent implements OnInit {

myfunc: any;

constructor(private PersistenceService: PersistenceService ){
}


ngOnInit() {

this.myfunc = new myfunction();



this.shaObj.generateIdentity().then(function (result, PersistenceService) {
console.log(PersistenceService.set('identityKey')); // getting undefined
}.bind(this.PersistenceService));

}

所以绑定(bind)服务似乎不起作用,如何将外部作用域“this”传递到“.then”函数中。

最佳答案

您应该使用this.injectableName而不是直接使用ClassName

console.log(PersistenceService.set('identityKey'));

应该是

console.log(this.PersistenceService.set('identityKey'));

Note: As per guideline and to avoid confusion use cammelCase for injected dependency

constructor(private persistenceService: PersistenceService ){}
<小时/>

您还可以使用 Arrow function 的 ES6 之美,而不是使用 .bind(this)

this.shaObj.generateIdentity().then((result, PersistenceService) => {
//Assuming you changed dependency name to `persistenceService`
console.log(this.persistenceService.set('identityKey'));
});

关于javascript - Promise then 函数中的 Angular 4 持久存储使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45360586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com