我正在尝试使用RazorPay的自定义结帐。
预期的行为
netBankingKeys 充满了许多银行
获取的从false更改为true
发生了什么
第一个setTimeout函数输出未定义的
第二个setTimeout函数表示该值为flase
第三个setTimeout函数按预期工作
我试图将超时值从4秒增加到20秒,但 netBankingKeys 仍然不确定。
ngOnInit() {
this.razorpay.once('ready', function (response) {
//Converts the object to array sets the global variable with the value
this.netbankingKeys = Object.keys(response.methods['netbanking']).map((key) => [{ name: response.methods['netbanking'][key], key: key }]);
//sets local storage with the stringify value
localStorage.setItem("banks", JSON.stringify(this.netbankingKeys));
//flag to say data was fetched initially false
this.fetched = true
})
//prints undefined
setTimeout(() => { console.log(this.netbankingKeys) }, 4000)
//prints false
setTimeout(() => { console.log(this.fetched) }, 4000)
//works fine
setTimeout(() => { console.log(localStorage.getItem("banks")) }, 4000)
}
答案 0 :(得分:0)
服务以访问本机浏览器窗口
import { Injectable } from '@angular/core';
function _window() : any {
// return the global native browser window object
return window;
}
@Injectable()
export class WindowRef {
get nativeWindow() : any {
return _window();
}
}
组件代码
import { Component, Inject, OnInit } from '@angular/core';
import { WindowRef } from "./core/services/winref.service";
import { Observable } from 'rxjs'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
fetched: Boolean = false;
rzp: any;
rzpObservable: Observable<any>;
netbankingkeys: any[];
title = 'app';
options = {
'key': "rzp_key",
//other fields if required
};
constructor(private winRef: WindowRef) {
this.rzp = new this.winRef.nativeWindow.Razorpay(this.options);
this.rzpObservable = Observable.create((observer: any) => {
this.rzp.once('ready', (response) => {
observer.next(response)
})
})
}
ngOnInit() {
this.rzpObservable.subscribe((response:any)=>{
this.netbankingkeys=Object.keys(response.methods['netbanking']).map((key) => [{ name: response.methods['netbanking'][key], key: key }]);
this.fetched=true;
})
setTimeout(() => { console.log(this.netbankingkeys) }, 4000)
setTimeout(() => { console.log(this.fetched) }, 4000)
}
}