How can I add Firebase Storage to my web app? - angularjs

I have created a small blog app using angular firebase so that registered user can login and post a blog with article and title. I want to make use of firebase storage so that user can upload images along with the article and title and user can also view the images related to post(store and retrieve feature) in real time.
Here is my html :
<div flex-xs="100" flex-md="80" layout="row" layout-wrap >
<h3 flex="100">Create Post</h3>
<md-input-container flex="40" >
<label>Title</label>
<input ng-model="article.title" type="text" />
</md-input-container>
<md-input-container flex="100" >
<label>Article</label>
<textarea ng-model="article.post" ></textarea>
</md-input-container>
<md-button class="md-raised md-primary" ng-click="AddPost()" ng-disabled="!article.title || !article.post">Publish</md-button>
</div>
Here is my controller :
.controller('AddPostCtrl', ['$scope','$firebase','$firebaseObject', '$firebaseArray', function($scope,$firebase,$firebaseObject,$firebaseArray) {
$scope.AddPost = function() {
var title = $scope.article.title;
var post = $scope.article.post;
var childRef = rootRef.child("Blog-One");
var list = $firebaseArray(childRef);
list.$add({
title: title,
post: post,
}).then(function(childRef) {
console.log(childRef);
}, function(error) {
console.log("Error:", error);
});
}
}])
Can anyone help me with how to implement firebase storage, please? Thanks in advance.

<div flex-xs="100" flex-md="80" layout="row" layout-wrap >
<h3 flex="100">Create Post</h3>
<md-input-container flex="40" >
<label>Title</label>
<input ng-model="article.title" type="text" />
</md-input-container>
<md-input-container flex="100" >
<label>Article</label>
<textarea ng-model="article.post" ></textarea>
</md-input-container>
Add these tags in your html
<progress value="0" max="100" id="uploader"></progress>
<input type="file" value="upload" id="fileButton"><br>
<md-button class="md-raised md-primary" ng-click="AddPost()" ng-disabled="!article.title || !article.post">Publish</md-button>
In your controller
var uploader=document.getElementById('uploader'),
imageUrl,
fileButton=document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file=e.target.files[0];
var storageRef=firebase.storage().ref('firebase').child(file.name);
var task=storageRef.put(file);
task.on('state_changed',
function progress(snapshot){
var percentage=( snapshot.bytesTransferred / snapshot.totalBytes )*100;
uploader.value=percentage;
if (percentage==100){
storageRef.getDownloadURL().then(function(url) {
Here you will get download url
imageUrl=url;
});
}).catch(function(error) {
// Uh-oh, an error occurred!
});
}
},
function error(err){
},
function complete(){
}
);
});
So you can allow all the users to post the article with an image. But keep one thing wait until the image uploaded in the storage, and then show the publish article button. To do that wait until the progress bar to get 100% then show the publish article button

Related

Angular: Unable to input data in text fields

Good Day, I'm using Angularjs 1.6.4 v with C# at back-end and I'm still new to this technology and learning.
Problem: I'm unable to input data in the text fields as given below.
<div layout="row" layout-xs="column">
<md-input-container class="md-icon-float md-block" flex>
<label>Name</label>
<md-icon md-font-icon="ion-ios-search"></md-icon>
<input ng-model="filter.name" type="text" ng-change="refreshContactTable()" ng-model-options='{ debounce: 500 }'>
</md-input-container>
<md-input-container class="md-icon-float md-block" flex>
<label>Contact No</label>
<md-icon md-font-icon="ion-ios-search"></md-icon>
<input ng-model="filter.contactNo" type="text" ng-change="refreshContactTable()" ng-model-options='{ debounce: 500 }'>
</md-input-container>
<md-input-container flex>
<label>Properties</label>
<md-icon md-font-icon="ion-ios-search"></md-icon>
<input ng-model="filter.property" type="text" ng-change="refreshContactTable()" ng-model-options='{ debounce: 500 }'>
</md-input-container>
</div>
I'm using Material angular as you can see my input fields are connected with ng-model which has filter function and it connect with resource services (model). Okay here is my angular code given below (ignore the property field)
$scope.landlordsTable = new ngTableParams(
{
page: 1,
count: 20,
filter: {
name: "",
contactNo: ""
}
},
{
getData: function ($defer, params) {
ContactsResourceService.get({
type: 'Landlord',
name: params.filter().name,
contactNo: params.filter().contactNo,
page: params.page(),
count: params.count()
}, function (data) {
if (data) {
params.total(data.total);
$defer.resolve(data.collection);
}
});
}
});
$scope.refreshContactTable = function () {
$scope.landlordsTable.reload();
}
Can anyone help me to sort out this issue. Thank you.

Why will my data not save my updated scope data from my form?

I have created a form in a modal which allows someone to enter in plan details. I have then created the scope form in ng-model attribute as you can see below...
<form>
<div class="form-group">
<label>{{plans.title}}</label>
<input type="text" name="title" ng-model="plans.title" class="form-control" placeholder="Enter Title" required />
</div>
<div class="form-group">
<label>{{plans.overview}}</label>
<textarea name="overview" ng-model="plans.overview" class="form-control" placeholder="Overview/Purpose" required />
</div>
<div class="form-group">
<label>{{plans.notes}}</label>
<textarea name="notes" ng-model="plans.notes" class="form-control" placeholder="Plan Notes" required />
</div>
<div class="form-group">
<label>{{plans.visualplan}}</label>
<div class="button" ngf-select ng-model="plans.visualplan" name="visualplan" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100" >Upload Visual Plan</div>
</div>
<div class="form-group">
<button type="submit" ng-click="submit()" Value="Post">Post</button>
</div>
</form>
In my code I am then trying to pull the data from the form into my scope object for plans under title, overview, notes and visualplan. Then i have coded this to upload the data from the form into my firebase json. However upon submitting the details, the upload to json process works correctly, but it is uploading the default values for title, overview, notes and visualplan which i have initiatlly set in my dailyplans.js file. What i want to upload is the details which I have attached through ng-model instead of the initial set values. Can anyone spot what I am doing wrong?
Below is my js file.
$scope.submit = function() {
$scope.plans = {
title: 'title',
overview: 'overview',
notes: 'notes',
visualplan: 'visual plan'
}
if (authData) {
ref.child('teaching-plans').child('teaching-plans' + authData.uid).set($scope.plans).then(function(authdata) {
console.log('successful');
}).catch(function(error) {
console.log(error);
});
}
}
You are resetting the plans object when user clicks on submit. Ideally it should be outside of submit method.
This is how you should do it
$scope.plans = {
title: 'title',
overview: 'overview',
notes: 'notes',
visualplan: 'visual plan'
}
$scope.submit = function(plans) {
if (authData) {
ref.child('teaching-plans').child('teaching-plans' + authData.uid).set(plans).then(function(authdata) {
console.log('successful');
}).catch(function(error) {
console.log(error);
});
}
}
And also update the html as
<div class="form-group">
<button type="submit" ng-click="submit(plans)" Value="Post">Post</button>
</div>
Hope this helps.
Just don't overwrite your plans object:
$scope.submit = function() {
$scope.plans.title = 'title';
$scope.plans.overview = 'overview';
$scope.plans.notes = 'notes';
$scope.plans.visualplan = 'visual plan;
if (authData) {
ref.child('teaching-plans').child('teaching-plans' + authData.uid).set($scope.plans).then(function(authdata) {
console.log('successful');
}).catch(function(error) {
console.log(error);
});
}
}
This way angular can fire the listeners correctly.

Click() function isn't working in protractor scripts

I'm trying to automate my tests with Protractor and Appium for an AngularJS site with jasmine framework in iPad simulator, sendkeys() function is working for username and password, but when i click into the login button the test is passed, but the action isn't done : no redirection to home page, and no on click effect is displayed for login button, i'm sure that element is located correctly ! because when i expect the gettext() to be equal to"LOGIN" it is passed but no redirection even if i put browser.sleep(8000);
Here my test script :
"use strict";
require("jasmine-expect");
var wd = require("wd");
describe('my app', function() {
it('should make the login test',function() {
// browser.ignoresynchronization=true;
browser.get("http://10.0.22.82:8080/jws/fetablet");
expect(browser.getCurrentUrl()).toEqual(("http://10.0.22.82:8080/jws/fetablet/#/login"));
element(by.model('credentials.username')).sendKeys('RET02').then(function(){
element(by.model('credentials.password')).sendKeys('RET02').then(function(){
element(by.css('.login-button')).click().then(function(){
browser.sleep(8000); expect(browser.getCurrentUrl()).not.toEqual("http://10.0.22.82:8080/jws/fetablet/#/login");
});
});
});
});
});
Is there another method to locate the click button correctly?
Here my html code :
​​<div class="lo​​gin_lang"> <md-button class="lang_button" ng-click="changeLang()">{{lang}}</md-button> </div>
<div layout="column" flex layout-align="center center" class="md-padding splash-background"> <div class="login-logo"> <img src="{{logoSrc}}"> </div> <form class="login-form" name="loginForm" ng-submit="login()">
<fieldset> <md-input-container class="md-block">
<label translate="login.USERNAME" ng-class="{'floating-label-rtl':dir==='rtl'}"
class="login-label">Username</label>
<input required ng-model="credentials.username" ng-focus="onFocus()" type="text">
<div ng-messages="loginForm.credentials.username.$error" ng-show="loginForm.credentials.username.$dirty">
<div ng-message="required" trans
​​late="login.MESSAGE_REQUIRED">This is required.</div> </div> </md-input-container> <md-input-container class="md-block"> <label ​​translate="login.PASSWORD" ng-class="{'floating-label-rtl':dir==='rtl'}"
class="login-label">Password</label> <input required ng-model="credentials.password" ng-focus="onFocus()" type="pa
​​ssword">
<div ng-messages="loginForm.credentials.password.$error" ng-show="loginForm.credentials.password.$dirty"> <div ng-message="required" translate="login.MESSAGE_REQUIRED">This is required.</div> </div> </md-input-container>
<div layout-align="center center" layout="column" ng-if="oneTimePassword"> <p class="login-otp-message" translate="login.OTP_MESSAGE">Enter the code which you received by SMS</p> <md-button class="md-warn login-otp-retry" translate="login.OTP_RETRY" ng-click="retry()">Retry</md-button> </div> <md-input-container class="md-block" ng-if="oneTimePassword"> <label translate="login.SECURITY_CODE" class="login-label">Security code</label> <input required ng-model="credentials.securityCode" ng-focus="onFocus()" type="password"> <div ng-messages="loginForm.credentials.securityCode.$error" ng-show="loginForm.credentials.securityCode.$dirty"> <div ng-message="required" translate="login.MESSAGE_REQUIRED">This is required.</div> </div> </md-input-container> <div layout-align="center"> <section layout-align="center" layout="row" layout-sm="column"> <div id="login-error" md-caption class="msg-error" ng-show="error" class="label">{{error}}</div>
​​
<md-button type="submit" class="md-raised login-button" ng-disabled="clicked" translate="login.LOGIN">Login</md-button> </section>
​​
</div> </fieldset> </form> <md-divider></md-divider> <footer class="login-footer"> <div layout="row" layout-align="center center"> <md-button ng-click="goToCustomerCare()" class="login-footer-link" translate="login.CUSTOMER_CARE">Contact Customer Care</md-button> <div> | </div> <md-button ng-click="showDisclaimer()" class="login-footer-link" translate="login.DISCLAIMER">Disclaimer</md-button> </div> </footer> </div>
​​I put the details of Appium recorder about the login button
There might be multiple reasons for that and it is going to be a guessing game anyway.
it could be that there is an another element matching the .login-button locator and you are clicking a different element. Let's improve the locator:
element(by.css(".login-form .login-button")).click();
wait for the element to be clickable:
var EC = protractor.ExpectedConditions;
element(by.model('credentials.username')).sendKeys('RET02');
element(by.model('credentials.password')).sendKeys('RET02');
var loginButton = element(by.css('.login-form .login-button'));
browser.wait(EC.elementToBeClickable(loginButton), 5000);
loginButton.click();
add a small delay before clicking the element (silly, but I see that helped sometimes):
element(by.model('credentials.username')).sendKeys('RET02');
element(by.model('credentials.password')).sendKeys('RET02');
browser.sleep(500);
element(by.css('.login-form .login-button')).click();
another silly try, click 2 times (I cannot believe I actually advise that):
var loginButton = element(by.css('.login-form .login-button'));
loginButton.click();
loginButton.click();
disable angular animations
click the button via browser.actions() moving to the element before the click:
var loginButton = element(by.css('.login-form .login-button'));
browser.actions().mouseMove(loginButton).click().perform();
sort of an extension to the previous approach. Move to element, sleep for half a second and then click:
browser.actions.mouseMove(loginButton).perform();
browser.sleep(500);
loginButton.click();
Or, if you would introduce a custom sleep() action, you can do:
browser.actions.mouseMove(loginButton).sleep(500).click().perform();
click the element via javascript:
var loginButton = element(by.css('.login-form .login-button'));
browser.executeScript("arguments[0].click();", loginButton);
And, after the form is submitted, instead of browser.sleep(), you can wait for URL to change explicitly, please see:
Protractor- Generic wait for URL to change
As a side note, in Protractor, you use the $ and $$ shortcuts for the CSS locators:
var loginButton = $('.login-form .login-button');
Try executing those commands without using the promise chain. It can be a problem in the previous chain.
"use strict";
require("jasmine-expect");
var wd = require("wd");
describe('my app', function() {
it('should make the login test',function() {
browser.get("http://10.0.22.82:8080/jws/fetablet");
expect(browser.getCurrentUrl()).toEqual(("http://10.0.22.82:8080/jws/fetablet/#/login"));
element(by.model('credentials.username')).sendKeys('RET02');
element(by.model('credentials.password')).sendKeys('RET02');
element(by.css('.login-button')).click();
browser.sleep(8000);
expect(browser.getCurrentUrl()).not.toEqual("http://10.0.22.82:8080/jws/fetablet/#/login");
});
PS: You can avoid using the 'then' function when you do not need to use the result of the method. It is controlled by the control flow
Just adding browser.sleep after the click worked for me:
it('Some test', function () {
element(by.css("button[type='submit']")).click();
browser.sleep(1000);
});
I have one more suggestion, you can expect particular element need to be displayed and clear the text-box. You can actually write in promise, that is the best way.
var loginButton = element(by.css('.md-raised.login-button'));
var userName = element(by.model('credentials.username'));
var password = element(by.model('credentials.password'));
this.username = function(sendUserName) {
expect(userName.isDisplayed()).toBeTruthy();
userName.clear().then(function(){
userName.sendKeys(sendUserName).then(function(){
expect(password.isDisplayed()).toBeTruthy();
});
});
};
this.password = function(password) {
expect(password.isDisplayed()).toBeTruthy();
password.clear().then(function(){
password.sendKeys(password).then(function(){
browser.wait(EC.elementToBeClickable(loginButton), 10000);
});
});
};
this.clickloginbutton = function() {
expect(loginButton.isDisplayed()).toBeTruthy();
loginButton.click().then(function(){
expect('something').not.toBeNull();
});
}
Tried to click the button twice and functionality wise it worked but throwed NoSuchElementError for the second click.
Made below adjustment and it worked for me
await browser.wait(EC.elementToBeClickable(element(by.css('selector')), 5000);
await $('selector').click();
if(await $(selector).isDisplayed())
await $(selector).click();

not getting any response from router to controller

login.controller
angular
.module('app.pages.auth.login')
.controller('LoginController', LoginController);
/** #ngInject */
function LoginController($http, $location)
{
var vm = this;
vm.submitPost = function(userData){
$http({
url: 'http://localhost:7200/api/pages/auth/login',
method: 'POST',
data: userData
}).then(function(res) {
if(res.data.success){
$location.path('/pages/profile');
console.log(res.data.message);
//vm.message=res.data.message;
} else {
//console.log(res.data.message);
//vm.message=res.data.message;
$location.path('/pages/auth/login');
}
}, function(error) {
alert('here');
});
};
}
api.js
router.get('/pages/auth/login', function(req, res) {
console.log(req.flash('loginMessage'));
res.render('auth/login/login.html', { message: req.flash('loginMessage') });
});
router.get('/pages/profile', isLoggedIn, function(req, res) {
return res.json({
success:true,
//message: 'Login Success',
})
res.render('profile/profile.html', {user:req.user });
});
I am not getting any response from router to controller. It shows the alert message 'here'. Is there any thing wrong done here? please help me to fix this.
login.html
<form name="loginForm">
<div class="alertmessage" >{{vm.message}}</div>
<md-input-container flex md-no-float>
<input ng-model="vm.form.username" placeholder="Username" translate
translate-attr-placeholder="LOGIN.USERNAME" name="username" required="true">
<div ng-messages="loginForm.username.$error" ng-show="loginForm.username.$touched">
<div ng-message="required">This field is required</div>
</div>
</md-input-container>
<md-input-container flex md-no-float>
<input ng-model="vm.form.password" type="password" placeholder="Password" translate
translate-attr-placeholder="LOGIN.PASSWORD" name="password" required="true">
<div ng-messages="loginForm.password.$error" ng-show="loginForm.password.$touched">
<div ng-message="required">This field is required</div>
</div>
</md-input-container>
<div class="remember-forgot-password" layout="row" layout-sm="column"
layout-align="space-between center">
<md-checkbox class="remember-me" ng-model="data.cb1" aria-label="Remember Me">
<span translate="LOGIN.REMEMBER_ME">Remember Me</span>
</md-checkbox>
<a ui-sref="app.pages_auth_forgot-password" class="forgot-password md-accent-color"
translate="LOGIN.FORGOT_PASSWORD">Forgot Password?</a>
</div>
<md-button class="md-raised md-accent" aria-label="LOG IN" translate="LOGIN.LOG_IN"
translate-attr-aria-label="LOGIN.LOG_IN"
ng-click="vm.submitPost(vm.form);">
LOG IN
</md-button>
</form>
Please verify what is the value of 'userData' coming from the front end/from where u r calling it. Seems there is an issue with that only!
If thats not the issue then please check the network in developer tools that why your service is failing?
To go to network(on chrome) click F12 >> Network.
Verify your service call and see whats the issue!
EDIT:
where is your 'headers' in service call? You intentionally din't add or you missed it?
This is one more image of network tabWhen i click after login it showed like this
Network tab image showing like this

PUT request in Angular not sending updated data within XHR Header

I am a beginner and new to AngularJS. I am trying to build an Edit/Update function.
The edit function doesn't do much, it just copies the model data to the Form inputs:
// Edit post
$scope.editPost = function(post){
$scope.title = post.title;
$scope.link = post.link;
};
The Update function should (after clicking the Update Button) take the edited data of the inputs, to update the post model:
// Update post
$scope.updatePost = function(post){
posts.update(post, {
title: $scope.title,
link: $scope.link
}).success(function() {
ToastService.show('Post updated');
});
};
The Edit Part works, when I edit the title input and click the Submit Button of the Edit Form, it sends a PUT request, but it seems to doesn't send the updated data within the PUT - it just sends a request with the original data.
The posts.js service:
angular.module('bidrp')
.factory('posts', [
'$http',
function($http){
var o = {
posts: [{title:"hey", upvotes:123}]
};
o.update = function(post) {
return $http.put('/posts/' + post.id, post).success(function(data){
o.posts.push(data);
});
};
Template where Post is displayed and editPost is triggered:
<div ng-repeat="post in posts | orderBy: '-upvotes'">
<md-button class="md-icon-button md-accent" aria-label="Vote-Up" ng-click="incrementUpvotes(post)">
<i class="material-icons">thumb_up</i>
</md-button>
{{post.upvotes}}
<span style="font-size:20px; margin-left:10px;">
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</span>
<span>
posted by <a ng-href="#/users/{{post.user.username}}">{{post.user.username}}</a>
</span>
<span>
Comments
Edit
Delete
</span><br>
<div ng-show="showEditForm" ng-include="'home/_edit-post.html'"></div>
</div>
<div ng-include="'home/_add-post.html'"></div>
_edit-post.html partial:
<form ng-submit="updatePost(post)">
<h3>Edit post</h3>
<div ng-include="'home/_form-post.html'"></div>
</form>
_form-post.html partial:
<md-input-container>
<label>Title</label>
<input required type="text" ng-model="title">
</md-input-container>
<md-input-container>
<label>Link</label>
<input type="text" ng-model="link">
</md-input-container>
<md-button type="submit" class="md-raised md-primary">Submit</md-button>
What am I doing wrong, how can I send the edited form data within the PUT request?
This is happening because, your, are just passing the original post object generated by ngRepeat to the update function not the $scope.post. When using ng-model="post" this will be attached to the $scope object.
You do not need the editPost function, the new data are already passed to $scope.title/$scope.title by ngModel directive (doing this will re-update the $scope.tile, $scope.link with the old values):
// Edit post
$scope.editPost = function(post){
$scope.title = post.title;
$scope.link = post.link;
};

Resources