在请求nodejs上初始化变量以构造Object

时间:2018-02-07 09:20:32

标签: javascript node.js typescript ecmascript-6 requestjs

我的变量有点问题。

我想在函数返回时构造Object(ObjectQueue),但我不能,因为在我的回调函数请求中初始化的变量没有相同的范围,我找不到解决方案。

变量资源,nameUser和JsonObject未定义。 有解决方案吗?

Plazza.ts

const request = require('request');
import { ObjectQueue } from '../ObjectQueue';
import { QueueService } from '../QueueService';

export class Plazza extends QueueService {

constructor() {
super('plazza');
}

getInfoFromService(username, password, url?, nameFile?): ObjectQueue {
console.log('username : ' + username);
console.log('password : ' + password);

let urlUsing = 'https://****.com/api/core/v3/people/email/' + username;
let nameFileUsing = 'user';

let resources: String[];
let nameUser:String;
let jsonObject:any;

if (url) {
  urlUsing = url;
}

if (nameFile) {
  nameFileUsing = nameFile;
}

const optionsUser = {
  url: urlUsing,
  auth: {
    password,
    user: username,
  },
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'user-agent': 'node.js', 'Allow-Control-Allow-Origin': '*',
  },
};

request(optionsUser, requestPlazza);

function requestPlazza(err, res, body) {
  if (err) {
    console.dir(err);
    return;
  }

  console.log('\nstatus code of ' + urlUsing + ' :', res && res.statusCode + '\n');

  jsonObject = JSON.parse(body);

  nameUser = jsonObject.name.familyName + '-' + jsonObject.name.givenName;

  const ressource = jsonObject.resources;
  for (const key in ressource) {
    if (ressource.hasOwnProperty(key)) {
      if (key === 'activity' || key === 'members') {
        console.log(key + ' : ' + ressource[key].ref);
        resources.push(ressource[key].ref);
      }
    }
  }
}
return new ObjectQueue(nameUser, this.nameService, nameFileUsing + '.json', jsonObject, resources);
}
}

ObjectQueue.ts

export class ObjectQueue {

public nameUser: string;
public nameService: string;
public nameFile: string;
public jsonObject: any;
public resources: string[];

 constructor(nameUser: string, nameService: string, nameFile: string, jsonObject: any, resources: string[]) {
   this.nameUser = nameUser;
   this.nameService = nameService;
   this.nameFile = nameFile;
   this.jsonObject = jsonObject;
   this.resources = resources;
 }
}

0 个答案:

没有答案