How do I chain promises before returning? - ionic-framework

Ok, I'm trying to encode image files to base64 and then make a POST to the API and return the response.
The trouble I'm having is, the base64 encodes run async, so it's not making the api post before the encoding has completed.
Any help appreciated.
makePost()
{
return Observable.create((observer) => {
this.myPost.base64images = new Array(10);
for (var i = 0; i < this.myPost.images.length; i++)
{
if (this.myPost.images[i])
{
this.base64.encodeFile(this.myPost.images[i].path).then((base64File: string) => {
this.myPost.base64images[i] = base64File;
}, (err) => {
this.myPost.base64images[i] = null;
});
}
}
observer.next(1);
observer.complete();
}).pipe(mergeMap((result) => {
var payload = {
PostTitle: "Hello",
Images: this.myPost.base64images
}
return this.apiService.makePost(payload).pipe(map(
response => {
return response;
},
err => {
return err;
}
));
}));
}

Related

Node.js named pipe C#

I am trying to make a NodeJS program and a c# communicate but I can't get the communication working. I think it used to work before but after an update, I needed to change the NodeJS code, and since I really don't have much experience with NodeJS I probably messed up something there. Help would be appreciated.
NodeJS code:
logCommand(req, resp) {
const { command } = req;
var PIPE_NAME = "mypipe";
var PIPE_PATH = "\\\\.\\pipe\\" + PIPE_NAME;
var server = net.createServer(function (stream) {
stream.on('data', function (c) {
});
stream.on('end', function () {
server.close();
});
});
server.on('close', function () {
server.close();
})
server.listen(PIPE_PATH, function () {
})
let logfile = fs.createWriteStream(path.join(config.Config.App.filesPath, 'CairossRun.txt'), {
flags: 'a',
autoClose: true
});
let text1 = `error\n\n`
if (resp.win_lose === 1) {
text1 = `Run: Succes\nTypeOfReward: NoRune\nEndOfTransmission\n\n`;
const rewards = resp.changed_item_list ? resp.changed_item_list : [];
if(rewards){
rewards.forEach(reward => {
if (reward.type === 8) {
text1 = `Run: Succces\nTypeOfReward: Rune\nRuneType: ${JSON.stringify(reward.info.rank)}\nRuneSlot: ${JSON.stringify(reward.info.slot_no)}\nRuneSet: ${JSON.stringify(reward.info.set_id)}\nRuneStars: ${JSON.stringify(reward.info.class)}\nEndOfTransmission\n\n`;
}
});
}
}
else {
text1 = `Run: Failed\nnEndOfTransmission\n\n`;
}
server.on('connection', function (stream) {
stream.write(text1);
})
server.on('drain', function (stream) {
stream.write(text1);
})
C# code:
public bool Connecting()
{
Console.WriteLine("connecting");
pipe = new NamedPipeClientStream(".", "mypipe", PipeDirection.In);
try
{
pipe.Connect(5000);
}
catch (TimeoutException e)
{
}
if (pipe.IsConnected)
{
Console.WriteLine("connected");
fileReader = new StreamReader(pipe);
return true;
}
else
return false;
}

My API is getting called 2 times In Ionic

I am working in my Ionic Project and my API is getting called 2 times. I am not able to get why my API is getting called 2 times.
This is my productdetails.html:
<ion-col *ngIf="hassizenot && product.out_of_stock == 0" style="padding: 0px;">
<button class="mybtn11" (click)="addtocartnew(product)" ion-button small>
Add to Cart
</button>
</ion-col>
This is my productdetails.ts:
addtocartnew(detailsp)
{
this.storage.get("ID").then((val) =>
{
if(val)
{
if(detailsp.SelectedSize)
{
let usercartnewdetails = {
user_id: val,
product_id: detailsp.id,
size: detailsp.SelectedSize,
};
this.restProvider.usercartproducts(usercartnewdetails, 'user_cart/'+detailsp.id+'/'+val+'/'+detailsp.SelectedSize).subscribe((data) => {
if (data) {
console.log("One");
this.responseEdit = data;
console.log(this.responseEdit.msg);
if (this.responseEdit.status === 'success') {
this.presentToast(detailsp.product_name);
}
else{
this.presentToasterror();
}
}
});
}
else
{
let usercartnewdetails = {
user_id: val,
product_id: detailsp.id,
};
this.restProvider.usercartproducts(usercartnewdetails, 'user_cart/'+detailsp.id+'/'+val).subscribe((data) => {
if (data) {
console.log("Two");
this.responseEdit = data;
console.log(this.responseEdit.msg);
if (this.responseEdit.status === 'success') {
this.presentToast(detailsp.product_name);
}
else{
this.presentToasterror();
}
}
});
}
}
});
}
This is my Service:
usercartproducts(credentials, type) {
var headers = new HttpHeaders();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('Content-Type','application/json');
headers.append('Access-Control-Allow-Credentials','true');
headers.append('Access-Control-Allow-Headers','Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
return this.http.post(apiUrl + type, credentials, {headers: headers});
}
In my ts file, I am running the API for adding the products to the cart and it is showing only one response in the console but it is calling 2 times because it is adding the 2 times the product and in the network in the chrome, it is calling 2 times.
Any help is much appreciated.
Just Try This In Your Service:
usercartproducts(credentials, type) {
var headers = new HttpHeaders();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('Content-Type','application/x-www-form-urlencoded');
headers.append('Access-Control-Allow-Credentials','true');
headers.append('Access-Control-Allow-Headers','Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
let v = new FormData();
for(var k in credentials)v.append(k,credentials[k]);
return this.http.post(apiUrl + type, v, {headers: headers});
}
This solved my problem.
because you implement yout API twice and your If condition must be wrong
change your ts like this.
addtocartnew(detailsp) {
if (detailsp.SelectedSize) {
this.storage.get("ID").then((val) => {
if (val) {
let usercartnewdetails = {
user_id: val,
product_id: detailsp.id,
size: detailsp.SelectedSize,
};
this.restProvider.usercartproducts(usercartnewdetails, 'user_cart/' +
detailsp.id + '/' + val + '/' + detailsp.SelectedSize).subscribe((data) => {
console.log("One");
this.responseEdit = data;
console.log(this.responseEdit.msg);
if (this.responseEdit.status === 'success') {
this.presentToast(detailsp.product_name);
}
else {
this.presentToasterror();
}
}
});
}
})
}
else {
this.storage.get("ID").then((val) => {
if (val) {
let usercartnewdetails = {
user_id: val,
product_id: detailsp.id,
};
this.restProvider.usercartproducts(usercartnewdetails, 'user_cart/' +
detailsp.id + '/' + val).subscribe((data) => {
if (data) {
console.log("Two");
this.responseEdit = data;
console.log(this.responseEdit.msg);
if (this.responseEdit.status === 'success') {
this.presentToast(detailsp.product_name);
}
else {
this.presentToasterror();
}
}
});
}
})
}
}
change as per your condition and it will work.

Callback is not a function NODEJS

I am trying learn nodejs and stumble upon this error
callback(null, removed);
TypeError: callback is not a function
It is a Steam trade bot, so when it send me an offer, I accept it but after that it crashes. What is wrong?
exports.removeOweNoTitle = (user, callback) => {
let file = 'data/users/' + user + '.json';
if(fs.existsSync(file)) {
let read = fs.createReadStream(file);
let data = "";
read.on('data', (chunk) => {
data += chunk;
});
read.on('end', () => {
let json;
try {
json = JSON.parse(data);
} catch(error) {
return callback(error);
}
let owe = {};
if(json.owe)
owe = json.owe;
else {
callback(null, 0);
return;
}
let removed = 0;
for(let game in owe) {
if(owe[game]) {
removed += owe[game];
owe[game] = 0;
}
}
let write = fs.createWriteStream(file, {flags: 'w'});
exports.clearNotifications(user, () => {
write.write(JSON.stringify(json), (error) => {
if(error)
return callback(error);
write.end();
});
return;
});
write.write(JSON.stringify(json), (error) => {
if(error)
return callback(error);
write.end();
});
write.on("finish", (callback, error) => {
callback(null, removed); //tady nebyl deklarován callback chyběl
});
});
} else {
generateUserFile(user);
callback(new Error('User\'s file is not defined!'), null);
}
}

Ionic formData append showing null in server

I am trying to upload an image using formData. The api is working fine. But the data is displaying null in the server.
My function is
capture_dl_front(){
this.camera.getPicture(this.cameraOptions)
.then(imageData => {
this.customer.dl_front = normalizeURL(imageData);
this.upload_dl_front(imageData);
}, error => {
this.func.showAlert('Error',JSON.stringify(error));
});
}
upload_dl_front(imageFileUri: any): void {
this.file.resolveLocalFilesystemUrl(imageFileUri)
.then(entry => (<FileEntry>entry).file(file => this.readFile_dl_front(file)))
.catch(err => console.log('Error',JSON.stringify(err)));
}
private readFile_dl_front(file: any) {
const reader = new FileReader();
reader.onloadend = () => {
const imgBlob = new Blob([reader.result], { type: file.type });
this.dl_front_imageUri = imgBlob;
this.dl_front_imageName = file.name;
alert(this.dl_front_imageName)
const img = new FormData();
img.append('image', this.dl_front_imageUri, this.dl_front_imageName)
this.api.test(img).then(data=>alert("final: "+data))
};
reader.readAsArrayBuffer(file);
}
and my api function is
test(image){
let headers = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
});
return new Promise( resolve => {
this.http.post(url, image, { headers: headers})
.subscribe(
data => {
resolve(data['message']);
},
error => {
resolve(error.statusText);
}
);
});
}
and i am getting the file in my laravel server as
$image = $request->file('image');
but i am getting null in the image parameter.
What am i doing wrong here?
You should remove the headers in the api call.
test(image){
return new Promise( resolve => {
this.http.post(url, image)
.subscribe(
data => {
resolve(data['message']);
},
error => {
resolve(error.statusText);
}
);
});
}

the tokenGetter method does not wait for the promise to be completed before attempting to process the token

I am using Jwt tokens for authentication and using a interceptor for adding access token to the requests.I have a getToken() method which is checking for token's validity and calling the service for getting new set of tokens. The method is returning promise but the requests are taking the promise before it gets completed and failing to get the updated token.
Below is my code:
export class TokenService {
refresh = false;
constructor(public injector: Injector) {
}
public getToken(): string | Promise<string> {
const jwtHelper = new JwtHelperService();
let token = localStorage.getItem('token');
let refreshToken = localStorage.getItem('refreshToken');
if (!token || !refreshToken) {
return null;
}
if (jwtHelper.isTokenExpired(token)) {
if (jwtHelper.isTokenExpired(refreshToken)) {
return null;
} else {
let tokenPromise;
if (!this.refresh) {
this.refresh = true;
tokenPromise = this.promiseFromObservable(this.getTokenService(localStorage.getItem('refreshToken')));
}
return tokenPromise;
}
} else {
return token;
}
}
getTokenService(refreshToken: string) {
let http = this.injector.get(HttpClient);
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Bearer ' + refreshToken
})
};
return http.post<Tokens>(location.origin + '/LiveTime/services/v1/auth/tokens?locale=en', null, httpOptions);
}
promiseFromObservable(o): Promise<string> {
return new Promise((resolve, reject) => o.subscribe((token: Tokens) => resolve(token.token),reject(), err => { console.log(err); return null; }))
.then((token: Tokens) => {
localStorage.setItem('token', token.token);
localStorage.setItem('refreshToken', token.refreshToken);
this.refresh = false;
return token.token;
},
err => { console.log(err); return null; }
)
.catch((error) => { console.log(error);reject();
});
}
}
Can someone tell me what is wrong in this code?