Shared service not fetching data after redirect back to the same page in Angular 7 - angular7

ngOnInit() {
this.sharedData.profileData.subscribe((data: any) => {
this.userDetails = data;
});
}
above code retrieve data when only page reloading. It gives me the old data when I redirect back to the same page after I add some data into the database from another component(page). If I reload the page, the service will give me correct data(Recent Data).
Ex -
scenario 1 - reload the home page
home page shows data = skills(Software Developer", "Photographer")
skills: (2) ["Software Developer", "Photographer"]
scenario 2 - redirect to add skill page
scenario 3 - add a new skill(let's say Designer) and redirect back to
the home page component
scenario 4 - show only the old data
data = skills(Software Developer", "Photographer")
skills: (2) ["Software Developer","Photographer"]
Error - It's not showing newly added skill(Designer)
It Should be skills: (3) ["Software Developer", "Photographer",Designer]
Shared Data Service tsfile
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs';
#Injectable()
export class SharedDataService {
private profileDataSource = new BehaviorSubject('');
profileData = this.profileDataSource.asObservable();
private publicProfileDataSource = new BehaviorSubject('');
publicProfileData = this.publicProfileDataSource.asObservable();
private skillDataSource = new BehaviorSubject('');
skillData = this.skillDataSource.asObservable();
constructor() { }
updateProfileData(data: any) {
this.profileDataSource.next(data);
}
addSkillData(data: any) {
const emitDataObj: any = {
type: 'ADD',
data: data
};
this.skillDataSource.next(emitDataObj);
}
updateSkillData(data: any) {
const emitDataObj: any = {
type: 'UPDATE',
data: data
};
this.skillDataSource.next(emitDataObj);
}
updatePublicProfileData(data: any) {
this.publicProfileDataSource.next(data);
}
}

Related

How to filter data from oDataModel in sapui5 after navigation to another view

I've tried different demo application of SAPUI5 like shoping cart, manage product. But I"m unable to solve my problem. I've two views. on home view I've set my model globally like
var model = this.getView().getModel('product');
var oModel = new sap.ui.model.json.JSONModel(model);
sap.ui.getCore().setModel(oModel, "product");
and then I'm navigating to product page. where i'm accessing my product name and trying to access my specific product to bind with my current view.
_routePatternMatched: function(oEvent) {
var name= oEvent.getParameter("arguments").name,
oView = this.getView(),
sPath = "/Product('" + sId + "')";
console.log(sPath);
var oModel = sap.ui.getCore().getModel("product");
var oData = oModel.getData(sPath);
console.log(oData);
oView.bindElement({
path: sPath,
events: {
dataRequested: function() {
oView.setBusy(true);
},
dataReceived: function() {
oView.setBusy(false);
}
}
});
//if there is no data the model has to request new data
if (!oData) {
oView.setBusyIndicatorDelay(0);
oView.getElementBinding().attachEventOnce("dataReceived", function() {
// reset to default
oView.setBusyIndicatorDelay(null);
this._checkIfCourseAvailable(sPath, name);
}.bind(this));
}
},
_checkIfCourseAvailable: function(sPath) {
var oModel = sap.ui.getCore().getModel("product");
var oData = oModel.getData(sPath);
// show not found page
if (!oData) {
this._router.getTargets().display("notFound");
}
},
I got the right result by filtering by id. now after giving path to var oData = oModel.getData(sPath);
console.log(oData); It have the right result but i'm unable to it do not show data on view i'm trying as {pruduct>/name}
pas model name in bindElement and then access via model name ..
oView.bindElement({
path: sPath,
model:modelName,
events: {
dataRequested: function() {
oView.setBusy(true);
},
dataReceived: function() {
oView.setBusy(false);
}
}
});
In view use {modelName>name}

SteamAuth var from startup.auth to the view ASP.NET

I want to get the profile information from steam. so first I've fixed that I can login through steam, I used this tutorial: http://www.oauthforaspnet.com/providers/steam/
But now I want to get the steam profile id from the user that logged in so I can use the JSON from the steam API to get the information from the user.
https://steamcommunity.com/profiles/(this id)
I hope someone can help me, I've searched for hours now, and don't have any result.
var options = new SteamAuthenticationOptions {
ApplicationKey = "Your API Key",
Provider = new OpenIDAuthenticationProvider // Steam is based on OpenID
{
OnAuthenticated = async context =>
{
// Retrieve the user's identity with info like username and steam id in Claims property
var identity = context.Identity;
}
}}; app.UseSteamAuthentication(options);
A while ago we discovered the answer:
1.) insert your key from the tutorial here:
var options = new SteamAuthenticationOptions
{
ApplicationKey = "Your API Key",
Provider = new OpenIDAuthenticationProvider // Steam is based on OpenID
{
OnAuthenticated = async context =>
{
// Retrieve the user's identity with info like username and steam id in Claims property
var identity = context.Identity;
}
}
};
app.UseSteamAuthentication(options);
2.) We discovered that steam is saving a users steam id in the database table called: 'AspNetUserLogins', the providerkey inside that table is an url made out of more pieces. For example:
http://steamcommunity.com/openid/id/here-users-steamid
We only need the users steamid, so we going to split that in step 3.
3.) Make a controller, for example: SteamController. Here we going to add a public string:
public string GetSteamID()
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new Steam.Models.ApplicationDbContext()));
var CurrentUser = manager.FindById(User.Identity.GetUserId());
if (User.Identity.Name != "")
{
string url = CurrentUser.Logins.First().ProviderKey;
ViewBag.steamid = url.Split('/')[5]; //here we going to split the providerkey so we get the right part
}
else
{
ViewBag.steamid = "";
}
return ViewBag.steamid;
}
) now we can add some stuff, lets say we going to add profile information. Go to your SteamController and add:
[HttpGet]
public ContentResult GetProfile()
{
string url = string.Format("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=addyourkeyhere&steamids={0}", this.GetSteamID());
string result = null;
using (var client = new WebClient())
{
result = client.DownloadString(url);
}
return Content(result, "application/json");
}
notice that you have to add your steam key from step 1 in the url.
) make a script called: profile.js. Here we going to add our profile information.
function profilepic() {
$.ajax({
url: 'http://localhost:3365/steam/GetProfile',
dataType: 'json',
success: function (data) {
$.each(data.response.players, function (key, value) {
if ($('.profile')) {
$('.profile').append("<img src='" + value.avatar + "'> <span>" + value.personaname + "</span>")
}
if ($('.profile1')) {
$('.profile1').append("<img src='" + value.avatarfull + "'>")
}
if ($('.username')) {
$('.username').append(value.personaname)
}
console.log(value)
});
}, error: function (httpReq, status, exception) {
console.log(status + " " + exception);
}
});
}
6.) Now we have to do the final step, create a view with the classes, for example:
<div class="userprofile">
<span class="profile1"></span>
<div class="userdescription">
<h2 class="username"></h2>
</div>
</div>
) I hope this will help some people, for more questions, feel free to ask!

Angularjs Rails Resource save() function not working from controller

I am using angularjs-rails-resource , in my Rails Angular App.
Account Resources
myApp.factory('Account', ['railsResourceFactory','railsSerializer', function
(railsResourceFactory,railsSerializer) {
return railsResourceFactory({
url: '/accounts',
name: 'account',
serializer: railsSerializer(function () {
this.nestedAttribute('address');
})
});
}]);
UserController.js
function userController($scope,$location,Auth,$rootScope,$http,Useraccount,Account) {
$scope.profileUpdate = function() {
//Useraccount.save(); // THIS WORKS
$scope.account = {}
$scope.account.save() // Throwing error : undefined function save
}
}
UserAccount Service
myApp.service('Useraccount',function(Auth,$location,$rootScope,Account){
var account;
var query = function(){
var promise = Account.query().then(function (results) {
account = results;
}, function (error) {
alert("Went Wrong while fetching User Account!!")
});
return promise;
}
var save = function() {
account.save().then(function (results) {
console.log(results);
}, function (error) {
alert("Went Wrong!!")
});
}
return {
query:query,
save:save
}
})
});
I am not sure why the save function from UserController is not working though I have imported Account resources as dependency. I did same in service , but it was working there. Any clue will be helpful.
You are actually calling the save() method for an empty javascript object. I don't see the point here.
Anyway you need an Angular object to do so. So either load account data from server.
$scope.accounts = Account.query(); // Will be an Array of accounts
Or create new instance of Account
$scope.account = new Account(); // An empty object

ASP.NET MVC Master Detail Entry Form

I’m trying to implement an order entry form using ASP.NET MVC but facing a lot of difficulties. All the samples that I found are related to viewing master detail forms, and none for adding or editing.
Suppose I have two tables: Order and OrderLines that are related to each others with one-to-many relationship. In the main view I had a “New” button when clicked it should show a new order view composed of the order fields, a grid that shows the order lines, and a “Save” button that when clicked will persist the whole order along with its lines into a database. The grid should have three buttons: “Add Line”, “Edit Line”, and “Delete Line”. When the “Add Line” is clicked a new view should be shown that allows the user to add the line to the order view grid lines –at this stage the database is not affected-. When the user clicks “Edit Line” a view will be shown that allows the user to edit the selected line and when done update the order grid lines.
The most difficult problems are:
How to pass the order and its lines collection between the order view and the order line views?
How to update the order view based on changes in the order line view?
And how to persist changes between views without the database being involved?
Is there a concrete example that shows how to implement this using MVC?
Your help and feedback is appreciated.
Pleas have a look at my blog post on creating master detail form in asp.net mvc. it also contains demo project that you can download
Unlike WebForms, ASP.NET MVC does not try to hide the stateless nature of HTTP. To work with a complex object across multiple forms you have a couple of options:
Save the object on the server with each change so that the updated object is available using only an id
Use jquery to populate the order line form and save details to the main form
I usually go with the client side option myself, with the main form having hidden fields for the data that will be edited in the subform. You may find the server side option easier though - if you really don't want to involve the database you can keep your partially updated object in the session.
Step 1: Create view model
public class OrderVM
{
public string OrderNo { get; set; }
public DateTime OrderDate { get; set; }
public string Description { get; set; }
public List<OrderDetail> OrderDetails {get;set;}
}
Step 2: Add javascript for add order lines
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
$(function () {
$('#orderDate').datepicker({
dateFormat : 'mm-dd-yy'
});
});
$(document).ready(function () {
var orderItems = [];
//Add button click function
$('#add').click(function () {
//Check validation of order item
var isValidItem = true;
if ($('#itemName').val().trim() == '') {
isValidItem = false;
$('#itemName').siblings('span.error').css('visibility', 'visible');
}
else {
$('#itemName').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#quantity').val().trim() != '' && !isNaN($('#quantity').val().trim()))) {
isValidItem = false;
$('#quantity').siblings('span.error').css('visibility', 'visible');
}
else {
$('#quantity').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#rate').val().trim() != '' && !isNaN($('#rate').val().trim()))) {
isValidItem = false;
$('#rate').siblings('span.error').css('visibility', 'visible');
}
else {
$('#rate').siblings('span.error').css('visibility', 'hidden');
}
//Add item to list if valid
if (isValidItem) {
orderItems.push({
ItemName: $('#itemName').val().trim(),
Quantity: parseInt($('#quantity').val().trim()),
Rate: parseFloat($('#rate').val().trim()),
TotalAmount: parseInt($('#quantity').val().trim()) * parseFloat($('#rate').val().trim())
});
//Clear fields
$('#itemName').val('').focus();
$('#quantity,#rate').val('');
}
//populate order items
GeneratedItemsTable();
});
//Save button click function
$('#submit').click(function () {
//validation of order
var isAllValid = true;
if (orderItems.length == 0) {
$('#orderItems').html('<span style="color:red;">Please add order items</span>');
isAllValid = false;
}
if ($('#orderNo').val().trim() == '') {
$('#orderNo').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#orderNo').siblings('span.error').css('visibility', 'hidden');
}
if ($('#orderDate').val().trim() == '') {
$('#orderDate').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#orderDate').siblings('span.error').css('visibility', 'hidden');
}
//Save if valid
if (isAllValid) {
var data = {
OrderNo: $('#orderNo').val().trim(),
OrderDate: $('#orderDate').val().trim(),
//Sorry forgot to add Description Field
Description : $('#description').val().trim(),
OrderDetails : orderItems
}
$(this).val('Please wait...');
$.ajax({
url: '/Home/SaveOrder',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
//clear form
orderItems = [];
$('#orderNo').val('');
$('#orderDate').val('');
$('#orderItems').empty();
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
error: function () {
alert('Error. Please try again.');
$('#submit').val('Save');
}
});
}
});
//function for show added items in table
function GeneratedItemsTable() {
if (orderItems.length > 0) {
var $table = $('<table/>');
$table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Rate</th><th>Total</th></tr></thead>');
var $tbody = $('<tbody/>');
$.each(orderItems, function (i, val) {
var $row = $('<tr/>');
$row.append($('<td/>').html(val.ItemName));
$row.append($('<td/>').html(val.Quantity));
$row.append($('<td/>').html(val.Rate));
$row.append($('<td/>').html(val.TotalAmount));
$tbody.append($row);
});
$table.append($tbody);
$('#orderItems').html($table);
}
}
});
</script>
Step 3: Create an action for save data
[HttpPost]
public JsonResult SaveOrder(OrderVM O)
{
bool status = false;
if (ModelState.IsValid)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
Order order = new Order { OrderNo = O.OrderNo, OrderDate = O.OrderDate, Description = O.Description };
foreach (var i in O.OrderDetails)
{
//
// i.TotalAmount =
order.OrderDetails.Add(i);
}
dc.Orders.Add(order);
dc.SaveChanges();
status = true;
}
}
else
{
status = false;
}
return new JsonResult { Data = new { status = status} };
}
you can download source code and video tutorial
You could try Telericks free MVC grid control...
http://demos.telerik.com/aspnet-mvc/grid/hierarchyserverside
Just off the top of my head (a kind of brain dump)...
You could have a main grid part of the form. This would be full view loaded from an action (either with an order number or not depending on loading an existing one or not).
When clicking an event (new or edit) this could open a partial view in a "lightbox" style. This would then pass back a json object back to the main form.
The passed json object would then be rendered using templating to the bottom of the table (for a new one) or update an existing record. This could also be saved back to the server in the same ajax call. Or just update the client side and need the user to click a save button.
An isDirty flag will be needed so any changes set it to true and the when the browser tries to leave or close etc. then you can prompt the user to save or not.
Hope this helps.
edit
Not tried this but could be interesting with the none db aspect of your question click
Step 3: Create an action for save data.
[HttpPost]
public JsonResult SaveOrder(OrderVM O)
{
bool status = false;
if (ModelState.IsValid)
{
using (ManageMobileStoreWebContext dc = new ManageMobileStoreWebContext())
{
//Random rnd = new Random();
//OrderID = rnd.Next(),
Order order = new Order { OrderNo = O.OrderNo, OrderDate = O.OrderDate, Description = O.Description };
foreach (var i in O.OrderDetails)
{
if(order.OrderDetails == null)
{
order.OrderDetails = new List<OrderDetail>();
}
// i.TotalAmount =
order.OrderDetails.Add(i);
//dc.OrderDetails.Add(i);
}
dc.Orders.Add(order);
dc.SaveChanges();
status = true;
}
}
else
{
status = false;
}
return new JsonResult { Data = new { status = status } };
}

Deleting multiple records in ASP.NET MVC using jqGrid

How can you enable multiple selection in a jqGrid, and also allow users to delete all of the selected rows using an ASP.NET MVC controller?
I have set the delete url property to my /Controller/Delete method, and this works fine if one record is selected. However, if multiple records are selected, it attempts to send a null value back to the controller where an integer id is required.
You can, but you have to write code for it:
deleteSelected: function(grid) {
if (!grid.jqGrid) {
if (console) {
console.error("'grid' argument must be a jqGrid");
}
return;
}
var ids = grid.getGridParam('selarrrow');
var count = ids.length;
if (count == 0) return;
if (confirm("Delete these " + count + " records?")) {
$.post("DeleteMultiple",
{ ids: ids },
function() { grid.trigger("reloadGrid") },
"json");
}
}
[HttpPost]
public ActionResult DeleteMultiple(IEnumerable<Guid> ids)
{
if (!Request.IsAjaxRequest())
{
// we only support this via AJAX for now.
throw new InvalidOperationException();
}
if (!ids.Any())
{
// JsonError is an internal class which works with our Ajax error handling
return JsonError(null, "Cannot delete, because no records selected.");
}
var trans = Repository.StartTransaction();
foreach (var id in ids)
{
Repository.Delete(id);
}
trans.Commit();
return Json(true);
}
I want to update this for MVC2 and jquery 1.4.2, if you want to pass array parameters to mvc2:
var ids = $("#grid").getGridParam('selarrrow');
var postData = { values: ids };
if (confirm("Delete these " + count + " records?")) {
$.ajax({
type: "POST",
traditional: true,
url: "GridDBDemoDataDeleteMultiple",
data: postData,
dataType: "json",
success: function() { $("#grid").trigger("reloadGrid") }
});
}
check http://jquery14.com/day-01/jquery-14 ajax part
thx

Resources