FormControl not patching values to multiple select - angularjs

I'm working on a angular application but I ran into a problem I cant find the solution to. I'm trying to patch some preselected values to a form control (mat-select multiple) but it just wont show the values. It works fine with the control above (food), but when I try to bind to the multiple choice list, the values wont show.
//Here is my code:
#Component({
selector: 'app-add-edit',
templateUrl: './add-edit.component.html',
styleUrls: ['./add-edit.component.less']
})
export class AddEditComponent implements OnInit {
pageTitle = '';
order: Order;
filteredUsers: User[] = [];
id: number;
orderToDisplay: Order = new Order();
orderForm: FormGroup = new FormGroup({
food: new FormControl('', [Validators.required]),
usersOrdering: new FormControl('', [Validators.required])
});
constructor(private dialogRef: MatDialogRef<AddEditComponent>,
private ordersService: OrdersService,
#Inject(MAT_DIALOG_DATA) public data: any,
private fb: FormBuilder) { }
usersSelected: User[];
ngOnInit(): void {
this.id = this.data.orderId;
if (this.id == 0) {
this.pageTitle = 'Add a new order';
this.order = new Order();
} else {
this.pageTitle = 'Edit the order';
this.getOrder(this.id);
}
this.filterUsers(this.id);
}
save(): void {
if (this.orderForm.valid) {
if (this.orderForm.dirty) {
this.usersSelected = this.orderForm.controls['usersOrdering'].value;
if (this.id == 0) {
this.order.food = this.orderForm.controls['food'].value;
this.order.orderCount = this.usersSelected.length;
this.order.restaurantId = this.data.restaurantId;
this.order.usersOrdering = this.usersSelected;
this.ordersService.addOrder(this.order)
.subscribe(data => {
this.dialogRef.close(true);
});
} else {
this.order.id = this.id;
this.order.food = this.orderForm.controls['food'].value;
this.order.orderCount = this.usersSelected.length;
this.order.usersOrdering = this.usersSelected;
this.ordersService.updateOrder(this.order)
.subscribe(data => {
this.dialogRef.close(true);
});
}
}
} else
console.log('form is invalid')
}
dismiss(): void {
this.dialogRef.close(false);
}
displayOrder(o: Order): void {
if (this.orderForm) {
this.orderForm.reset();
}
this.order = o;
console.log(this.order.usersOrdering);
this.orderForm.patchValue({
food: this.order.food,
usersOrdering: this.order.usersOrdering
});
this.orderForm.updateValueAndValidity();
}
filterUsers(orderId: number) {
this.ordersService.filterUsers(orderId)
.subscribe(data => {
this.filteredUsers = data;
});
}
getOrder(id: number) {
this.ordersService.getOrder(id)
.subscribe(data => {
this.order = data;
this.displayOrder(this.order);
});
}

Related

Flutter - nested json from API

I am still new to flutter development and recently I've been trying to call API. I've managed to do so without placing data into the model and it worked fine. The issue is when I try to serialize the data. I've created a model using webinovers
https://run.mocky.io/v3/5c648026-c95a-4cf8-9a14-79f13cfb29d3
json data
{
"problems": [{
"Diabetes":[{
"medications":[{
"medicationsClasses":[{
"className":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}],
"className2":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}]
}]
}],
"labs":[{
"missing_field": "missing_value"
}]
}],
"Asthma":[{}]
}]}
here is my code
problem_models
class AllProblem {
late List<Problem>? problems;
AllProblem({this.problems});
AllProblem.fromJson(Map<dynamic, dynamic> json) {
if (json['problems'] != null) {
problems = <Problem>[];
json['problems'].forEach((v) { problems!.add( Problem.fromJson(v)); });
}
}
}
class Problem {
late List<Diabete> diabetes;
late List<Asthma> asthma;
Problem.fromJson(Map<dynamic, dynamic> json) {
if (json['Diabetes'] != null) {
diabetes = <Diabete>[];
json['Diabetes'].forEach((v) { diabetes.add( Diabete.fromJson(v)); });
}
if (json['Asthma'] != null) {
asthma = <Asthma>[];
json['Asthma'].forEach((v) { asthma.add( Asthma.fromJson(v)); });
}
}
}
class Diabete {
late List<Medication> medications;
late List<Labs> labs;
Diabete.fromJson(Map<dynamic, dynamic> json) {
if (json['medications'] != null) {
medications = <Medication>[];
json['medications'].forEach((v) { medications.add( Medication.fromJson(v)); });
}
if (json['labs'] != null) {
labs = <Labs>[];
json['labs'].forEach((v) { labs.add( Labs.fromJson(v)); });
}
}
}
class Medication {
late List<MedicationsClass> medicationsClasses;
Medication.fromJson(Map<dynamic, dynamic> json) {
if (json['medicationsClasses'] != null) {
medicationsClasses = <MedicationsClass>[];
json['medicationsClasses'].forEach((v) { medicationsClasses.add( MedicationsClass.fromJson(v)); });
}
}
}
class MedicationsClass {
late List<ClassName> className;
late List<ClassName> className2;
MedicationsClass.fromJson(Map<dynamic, dynamic> json) {
if (json['className'] != null) {
className = <ClassName>[];
json['className'].forEach((v) { className.add( ClassName.fromJson(v)); });
}
if (json['className2'] != null) {
className2 = <ClassName>[];
json['className2'].forEach((v) { className2.add( ClassName.fromJson(v)); });
}
}
}
class ClassName {
late List<AssociatedDrug> associatedDrug;
late List<AssociatedDrug> associatedDrug2;
ClassName.fromJson(Map<dynamic, dynamic> json) {
if (json['associatedDrug'] != null) {
associatedDrug = <AssociatedDrug>[];
json['associatedDrug'].forEach((v) { associatedDrug.add( AssociatedDrug.fromJson(v)); });
}
if (json['associatedDrug#2'] != null) {
associatedDrug2 = <AssociatedDrug>[];
json['associatedDrug#2'].forEach((v) { associatedDrug2.add( AssociatedDrug.fromJson(v)); });
}
}
}
class AssociatedDrug {
late String name;
String? dose;
late String strength;
AssociatedDrug.fromJson(Map<dynamic, dynamic> json) {
name = json['name'];
dose = json['dose'];
strength = json['strength'];
}
}
class Labs {
late String missingField;
Labs.fromJson(Map<dynamic, dynamic> json) {
missingField = json['missing_field'];
}
}
class Asthma {
Asthma();
Asthma.fromJson(Map<dynamic, dynamic> json) {
}
Map<dynamic, dynamic> toJson() {
final Map<dynamic, dynamic> data = <dynamic, dynamic>{};
return data;
}
}
resposiory_problem
import 'package:mvvp_simple/model/problems_model.dart';
abstract class ProblemsRepository{
Future<List<AllProblem>> getAllProblem();
}
this is resposiory_problem_API
import 'dart:convert';
import 'package:mvvp_simple/model/problems_model.dart';
import 'package:mvvp_simple/repository/problem/problems_repository.dart';
import 'package:http/http.dart' as http;
class ProblemsAPI extends ProblemsRepository{
//late AllProblem allProblem;
#override
Future<List<AllProblem>> getAllProblem() async{
List<AllProblem> problemList =[];
var apiURl = 'https://run.mocky.io/v3/5c648026-c95a-4cf8-9a14-79f13cfb29d3';
var response = await http.get(Uri.parse(apiURl));
if (response.statusCode == 200) {
var data = await jsonDecode(response.body.toString());
problemList = data.map((problems)=> AllProblem.fromJson(problems));
for(Map i in data){
problemList.add(AllProblem.fromJson(i));
}
print(problemList);
}
return problemList;
}
}
widget to fetch data
child: FutureBuilder(
future: HomeViewModel().fetchAllProblem(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Loading();
} else {
print('this data loaded ${snapshot.data}' );
var problems = snapshot.data;
return Center(
child: ListView.builder(
itemCount: problems?.length,
itemBuilder: (context, index) => const ListTile(title: Text('Problem'),subtitle: Text('Medications'),),
));
}
},
))

Private Values on Angular Factory

I have private values on my Factory service, but when I update a private value in one instance, all instances are updated as well.
Whats the best way to accomplish that without Updating all instances:
angular.module('app').factory('instanceItem', function () {
var _valid = true;
var item = function (id,data){
this.id = id;
this.data = data;
};
item.prototype.setValid = function(bool) {
_valid = bool;
}
item.prototype.getValid = function() {
return _valid
}
return { item:item }
});
What I am getting:
var itemA = new instanceItem.item(1,{});
var itemB = new instanceItem.item(2,{});
itemA.setValid(false);
console.log(itemA.getValid());
//False
console.log(itemB.getValid());
//False
What I am looking for
var itemA = new instanceItem.item(1,{});
var itemB = new instanceItem.item(2,{});
itemA.setValid(false);
console.log(itemA.getValid());
//False
console.log(itemB.getValid());
//True
A service is a singleton. So there is a unique instance of _valid. _valid should be a field of item:
var item = function (id,data){
this.id = id;
this.data = data;
this._valid = true;
};
item.prototype.setValid = function(bool) {
this._valid = bool;
}
item.prototype.getValid = function() {
return this._valid;
}
Or, if you really want to make it private (and also make your service more natural to use):
function createItem(id, data) {
var _valid = true;
return {
id: id,
data: data,
setValid: function(bool) {
_valid = bool;
},
getValid: function() {
return _valid;
}
};
}
return { createItem: createItem }

Angular 2 dictionary

In Angular 1 my code looked like this:I have 2 dictionaries and functions
var rus = {"hello" : "привет",
"text":"текст",
"home":"дом"};
var eng = {"hello":"hello",
"text":"text",
"home":"home"};
$scope.selectedLang = rus;
translate();
function translate() {
$scope.hello = $scope.selectedLang["hello"];
$scope.text = $scope.selectedLang["text"];
$scope.home = $scope.selectedLang["home"];
}
$scope.switchLang = function(lang) {
if(lang == "rus") {
$scope.selectedLang = rus;
} else {
$scope.selectedLang = eng;
}
translate();
};
But now I need to make this in angular 2. How can I do this?
I have included only class logic here,hope this helps:
export class AppComponent implements OnInit{
public hello:any;
public text:any;
public home:any;
private rus = {
"hello" : "привет",
"text":"текст",
"home":"дом"
};
private eng = {
"hello":"hello",
"text":"text",
"home":"home"
};
private selectedLang:any;
ngOnInit(){
this.selectedLang = this.rus;
this.switchLang('rus'); //calling switchLang() method
}
private selectedLang = this.rus;
translate() {
this.hello = this.selectedLang["hello"];
this.text = this.selectedLang["text"];
this.home = this.selectedLang["home"];
}
switchLang (lang:string){
if(lang == "rus") {
this.selectedLang = this.rus;
} else {
this.selectedLang = this.eng;
}
this.translate();
}
}

how can i inject IContentManager in Timer callback (Orchard CMS)

public Models.ManagedUsersPart GetManagedUsers(int ManagedUsersId)
{
return _cacheManager.Get(ManagedUsersId, ctx =>
{
MonitorManagedUserSignal(ctx, ManagedUsersId);
Timer = new Timer(t => DoUpdate(_contentManager,ManagedUsersId), "c", TimeSpan.FromMinutes(2), TimeSpan.FromMilliseconds(-1));
var managedusers = _contentManager.Get<ManagedUsersPart>(ManagedUsersId);
return managedusers;
});
}
and this is my DoUpdate function:
public void DoUpdate(IContentManager contentmanager,int ManagedUsersId)
{
var transation = _iworkcontext.CreateWorkContextScope().Resolve<ITransactionManager>();
transation.RequireNew();
var manager = getmanager();
var modifiemanageruser = manager.Get<ManagedUsersPart>(ManagedUsersId);
var modi = GetManagedUsers(ManagedUsersId);
modifiemanageruser.InvitedCount = modi.InvitedCount;
}
and ,this is my getmanager function:
public IContentManager getmanager()
{
if (Timermanager == null)
{
Timermanager = _iworkcontext.CreateWorkContextScope().Resolve<IContentManager>();
}
return Timermanager;
}
The question is "modifiemanageruser.InvitedCount = modi.InvitedCount"
this code does not persist update to database,anyone can help?

how to do something when data from service is ready in angular?

I create service like this :
export class MDCurrencyService implements IMDCurrencyService {
httpService: ng.IHttpService;
handlerUrl: string;
constructor($http: ng.IHttpService) {
this.httpService = $http;
this.handlerUrl = '/Master/';
}
get(): MDCurrency[]{
var result: MDCurrency[] = [];
var resp: ng.IPromise<any> = this.httpService.get(this.handlerUrl +'GetAllCurrency')
.then((response: any): ng.IPromise<any> => this.handlerResponded(response, null));
resp.then((data) => {
if (data.is_success) {
data.data.forEach(c => {
var converted: MDCurrency = <MDCurrency>c;
converted.selectedCountry = null;
converted.selectedStatus = null;
result.push(converted);
});
return result;
}
else return null;
});
return result;
}
handlerResponded(response: any, params: any): any {
response.data.requestParams = params;
return response.data;
}
}
in my controller :
$scope.currencies = this.currencies = mdCurrencyService.get();
if ($scope.currencies.length > 0) {
console.log('entered'); //never executed
$scope.currencies.forEach(currency => {
for (var ii = 0; ii < this.statuses.length; ii++)
if ($scope.statuses[ii].Id == currency.Status)
currency.selectedStatus = this.statuses[ii];
});
}
but after $scope.currencies filled from service that forEach never executed.
how to execute that code when $scope.currencies is filled by data from service?
mdCurrencyService.get() should be implemented as an asynchronous service returning a promise. It can be utilized this way:
mdCurrencyService.get().then(function (currencies) {
// process result here
$scope.currencies = currencies;
});

Resources