0

I have a little bit problem with my variables.

I would like construct Object (ObjectQueue) at return on my function but i can't because variables initalized in my callback function request have no the same scope and i don't find solution.

The variables resources, nameUser and JsonObject are undefined. Have you solution please ?

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;
 }
}
Jerem
  • 1
  • 2
  • You can't have the return value of `getInfoFromService` directly include results from the request as it's an async operation. You either need to return a `Promise` or use a callback. – Matt R. Wilson Feb 08 '18 at 08:47
  • ok i success on using request-promise. I put my object on promise – Jerem Feb 09 '18 at 08:58

0 Answers0