ionic 3 - can't create alert inside http request - http

So I'm using the native HTTP cordova plugin for my http requests. But I can't seem to wrap my head around a problem where I can't create an alert inside the onFail function. Anyone else experienced this?
The error says:
Error in Error callbackId: CordovaHttpPlugin1608257770 : TypeError: Cannot
read property 'alertCtrl' of undefined
Here's how I structured my code:
cordova.plugin.http.sendRequest('http://127.0.0.1:5000/api/login/', options, function(response) {
try { //onSuccess
response.data = JSON.parse(response.data);
localStorage.setItem('token', JSON.stringify(response.data.token));
} catch(e) {
console.error('JSON parsing error');
}
}, function(response) { //onFail
console.log('403');
let alert = this.alerts.create({
title: 'Error',
subTitle: 'Username/password is invalid!',
buttons: ['Dismiss']
});
alert.present();
}
);
Here's how my constructor looks like:
constructor(public navCtrl: NavController,
private alerts: AlertController,
private http: HTTP,
private store: Storage,
) {}
What's causing it to not work?

Try this, because when you create alert in request "this" means httprequest so that hasn't alert class
let alert = this.alerts.create({
title: 'Error',
subTitle: 'Username/password is invalid!',
buttons: ['Dismiss']
});
cordova.plugin.http.sendRequest('http://127.0.0.1:5000/api/login/', options, function(response) {
try { //onSuccess
response.data = JSON.parse(response.data);
localStorage.setItem('token', JSON.stringify(response.data.token));
} catch(e) {
console.error('JSON parsing error');
}
}, function(response) { //onFail
console.log('403');
alert.present();
}
);

Related

App redirects PUT method (Laravel + VUE3 + inertia)

From Ideas/Show.vue component I am updating the idea entry. Selected approach:
<script>
import { Head, useForm } from '#inertiajs/inertia-vue3';
export default {
props: {
idea: {
type: Object,
required: true,
},
},
data() {
return {
ideaEditForm: useForm({
title: this.idea.title,
description: this.idea.description,
}),
edit: false,
}
},
methods: {
cancelEdit() {
this.edit = false;
this.ideaEditForm.title = this.idea.title;
this.ideaEditForm.description = this.idea.description;
},
updateIdea() {
this.ideaEditForm.put(route('ideas.update', this.idea.id), {
onSuccess: () => {
alertify.success('Success!');
this.ideaEditForm.reset();
},
});
},
},
}
</script>
the controller update method:
public function update(Idea $idea, UpdateIdeaRequest $request) {
$idea->update($request->validated());
return redirect()->back();
}
When I update idea I get error. The ideas/1/8 method is not supported for route PUT. Supported methods: GET, HEAD. Why is it using PUT method? I thought maybe redirect()->back()
has some quirks I am unaware about, but same thing happens with return redirect()->route('ideas.show', [$idea->information_system_id, $idea->id]);

How to get the value of a callback outside the upload function of the Vimeo class?

I'm very new to js and I'm learning Nestjs. I'm building an API to work with the Vimeo API using their Vimeo lib. To upload a video, the Vimeo class has a method called upload:
upload(
file: string | File,
params: object,
completeCallback: UriCallback,
progressCallback: ProgressCallback | undefined,
errorCallback: ErrorCallback,
): void;
upload(
file: string | File,
completeCallback: UriCallback,
progressCallback: ProgressCallback | undefined,
errorCallback: ErrorCallback,
): void;
On my service, I used it like:
async uploadVideo(#Body() video: UploadVideoDto): Promise<string> {
let videoUri: string;
this.client.upload(
video.pathToFile,
{
name: video.name,
description: video.description,
},
function (uri) {
console.log(uri);
videoUri = uri;
},
function (bytesUploaded, bytesTotal) {
console.log(bytesUploaded, bytesTotal);
},
function (error) {
throw new Error(error);
},
);
return videoUri;
}
The function (uri) { console.log(uri) } is the callback function when the upload finishes and it gives the uri that the video was uploaded to. I tried to get it on my controller, like this:
#Post('/upload')
async upload(#Body() video: UploadVideoDto) {
await this.appService.uploadVideo(video).then(function (uri): void {
console.log(uri);
});
}
The problem is that the console.log(uri) always prints undefined. How can I get that callback return from my service to my controller?
if uploadVideo should return a Promise that resolves to an string (the uri), it could be like this:
async uploadVideo(video: UploadVideoDto): Promise<string> {
return new Promise<string>((resolve, reject) => {
this.client.upload(
video.pathToFile,
{
name: video.name,
description: video.description,
},
function (uri) {
resolve(uri)
},
function (bytesUploaded, bytesTotal) {
console.log(bytesUploaded, bytesTotal);
},
function (error) {
reject(error)
},
);
})
}
Learn about JS async/await feature.

Get an error from Angular2 http in Es5

I am trying to use http with Angular2.
Here is my code:
var _domain = 'http://localhost:3000/';
app.Applications = ng.core.Injectable().Class({
constructor: [ng.http.Http, function(http) {
this.http = http;
this.emailExistUrl = _domain + 'api/applications/email';
}],
doesEmailExist: function(email) {
var data = { email: email };
return this.http.post(this.emailExistUrl, data)
.toPromise()
.then(function(response) { response.json().data; })
.catch(this.handleError);
}
});
The main component:
app.AppComponent = ng.core
.Component({
selector: 'register-form',
templateUrl: 'src/register/app.component.html',
providers: [app.Applications]
})
.Class({
constructor: [ng.core.ElementRef, app.Applications, function(ref, Applications) {
this.programs = JSON.parse(ref.nativeElement.getAttribute('programs'));
this.applications = Applications;
}],
doesEmailExist: function(email) {
return this.applications.doesEmailExist(email);
}
});
Here is main.js file:
document.addEventListener('DOMContentLoaded', function() {
ng.platformBrowserDynamic.bootstrap(app.AppComponent, [
ng.forms.disableDeprecatedForms(),
ng.forms.provideForms(),
ng.http.HTTP_PROVIDERS,
]);
});
When doesEmailExist is called I get an error from the http module:
vendor-client.min.js:55470 TypeError: Cannot read property 'platform_browser_private' of undefined
Any ideas?
FIXED:
Http was before platform-browser on the script tag list. :/
<script src="https://npmcdn.com/#angular/http/bundles/http.umd.js"></script>
<script src="https://npmcdn.com/#angular/platform-browser/bundles/platform-browser.umd.js"></script>
<script src="https://npmcdn.com/#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js"></script>
The inverse is better :)
Try to assign http at the beginning of the constructor:
app.Applications = ng.core.Injectable().Class({
constructor: [ng.http.Http, function(http) {
this.http = http;
...
}],
doesEmailExist: function(email) {
...
}
});
EDIT
See this Plunker: http://plnkr.co/edit/aQWqxauklT7MqSjfhLFD. To simplify, I have put everything in main.js file, and instead of an http post I have implemented an http get. However, locally, even the http post works with a web service API. I hope it's helpful to solve your problem.

http into a service with Angular2 with es5

I am working with Angular2 and es5. I want to use http in a service.
Unfortunately I have 2 errors:
- http is undefined, but ng.http.Http is defined,
- I have this error for the main component:
vendor-client.min.js:28 EXCEPTION: Can't resolve all parameters for class0: (t, ?)
Here is my service code:
;(function(app, ng) {
console.log(new ng.http.Http());
app.ApplicationsService = ng.core.Injectable().Class({
constructor: [ng.http.Http, function(http) {
console.log(http);
this.applicationsEmailUrl = 'api/applications/email';
this.http = http;
}],
emailExists: function(email) {
console.log(email);
var data = { email: email };
return this.http.post(this.applicationsEmailUrl, data)
.toPromise()
.then(function(response) { response.json().data; })
.catch(this.handleError);
}
});
})(window.app || (window.app = {}), window.ng);
Here is the main component:
;(function(app, ng) {
app.AppComponent = ng.core
.Component({
selector: 'register-form',
templateUrl: 'src/register/app.component.html'
})
.Class({
constructor: [ng.core.ElementRef, app.ApplicationsService, function(ref, Applications) {
console.log('app.component.js');
this.programs = JSON.parse(ref.nativeElement.getAttribute('programs'));
this.applications = Applications;
}],
emailExists: function(email) {
console.log('emailExists() triggered');
Applications.emailExists(email);
}
});
})(window.app || (window.app = {}), window.ng);
The bootstrap:
;(function(app, ng) {
document.addEventListener('DOMContentLoaded', function() {
ng.platformBrowserDynamic.bootstrap(app.AppComponent, [
ng.forms.disableDeprecatedForms(),
ng.forms.provideForms(),
ng.http.HTTP_PROVIDERS,
app.ApplicationsService
]);
});
})(window.app || (window.app = {}), window.ng);
If I try to inject http into the main component within the providers array, it works. But I would rather prefer to have a service.
I found out the problem. Looks like Angular2 needs to load your code in order. The main component was loaded before the service, so it was undefined. I put all my code in one file and it works. I will use a require loader asap.

In Meteor when trying to access an attribute, I get TypeError: Cannot read property in the console. But the site is working

When trying to read an attribute, meteor gives me a TypeError: Cannot read property 'featuredImage' of undefined error in the browser console. But it reads featuredImage and the site is working fine. How can I get rid of this error? Is it happening because my subscriptions are not yet ready? Is that's the case, how to fix it? (PS : Im using the flow router so I can't wait for subscriptions in the router)
My template code :
Template.About.helpers({
page: () => {
return findPage();
},
featuredImage: () => {
var thisPage = findPage();
return Images.findOne({
"_id": thisPage.featuredImage
});
}
});
function findPage() {
return Pages.findOne({
slug: 'about'
});
}
The router code :
FlowRouter.route('/about', {
name: 'about',
subscriptions: function() {
this.register('page', Meteor.subscribe('pages', 'about'));
this.register('image', Meteor.subscribe('images'));
},
action() {
BlazeLayout.render('MainLayout', {
content: 'About'
});
setTitle('About Us');
},
fastRender: true
});
The subscription is probably not ready yet. FlowRouter provides a utility for dealing with this, your helpers should look like this:
Template.About.helpers({
page: () => {
// If you only need a specific subscription to be ready
return FlowRouter.subsReady('page') && findPage() || null;
},
featuredImage: () => {
// Ensure ALL subscriptions are ready
if ( FlowRouter.subsReady() ) {
var thisPage = findPage();
return Images.findOne({
"_id": thisPage.featuredImage // Probably should be thisPage.featuredImage._id
});
}
return null;
}
});
However, for maximum performance, you should use if (FlowRouter.subsReady('page') && Flowrouter.subsReady('image')) rather than FlowRouter.subsReady() since if you have other pending subscriptions which are large, it will wait for those even though you don't need them.

Resources