I am working on an Angular2 application and one of the #Components has a button that when clicked will send a post request to my server which will either respond with an Ok(string) or a BadRequest(string).
I am having trouble updating an #Input field of one of my #Components after getting the answer from the server.
Below are simplified version of some of my classes.
My Component class
#Component({
moduleId: module.id,
selector: 'model-comp',
templateUrl: './model.component.html',
styleUrls: ['./model.component.css']
})
export class MyComponent{
#Input() model: Model;
#Output() emitter: EventEmitter<Model> = new EventEmitter<Model>();
public constructor(private service: MyService){}
public toggle(): void {
this.service.send(model.id, model.name){
.subscribe(
result => this.onSuccess(result)),
error => this.onError(error),
() => this.onComplete());
}
public onSuccess(result: string): void {
if(result.inculdes("Some Text")) this.model.flag = true;
else this.model.flag = false;
this.emitter.emit(this.model);
}
public onError(error: any): void {
//notification using bootstrap-notify
}
public onComplete(): void {
//currently empty
}
}
My Service class
export class MyService{
public send(id: string, name: string){
return <Observable<string>>this.http
.post('url', new Dto(id, name))
.map(result => this.getData<string>(result))
.catch(this.catchBadResponse);
}
private getData<E>(result: Response): E {
//checking if result.status is ok
var body = result.json ? res.json(): null;
return <E>(body || {});
}
private catchBadRespomse: (error: any) => Observable<any> = (error: any) => {
var response = <Response>error;
var json = response.json();
var msg = json.Message;
var errormsg = json?
(json.error ? json.error: JSON.stringify(msg?msg:json)) :
(response.statusText || 'Error?');
return Obserable.of(errormsg);
}
}
Template of MyComponent
<button (click)="toggle()"
[ngClass]="{'class1': true, 'class2': model.flag}">Text</button>
Template of Parent Component
<div *ngFor="let model of getList()">
<model-comp [model]="model" (emitter)="onEmit($event)"></model-comp>
</div>
The onEmit Function
onEmit(evt: any): void{
if(evt instanceof Model){
var evtModel = evt as Model;
this.list.find(search => search.id == evtModel.id)
.isFav = evtModel.isFav;
}
}
The problem is that even though I post my data and receive the response, The property flag of my model does not change.
I think that the click event reloads the component thus removing the observers of the EventEmitter.
So is there any way to cancel the reload, not lose the observers of the EventEmitter or any other way to update the root object or the element class?
update (see comments below the question)
If getList() (what *ngFor binds to) returns a new list every time it is called, *ngFor will be permanently busy rerendering the items because change detection will cause getList() being called again and again.
Binding to a function that returns a new object or array every time it's called directly will cause serious issues like exceptions and dramatic performance degredation.
Using method/function calls in the view is strongly discouraged in general. Rather assign the list to a field and bind to that field instead of the method.
ngOnInit() is fine for initializing the list but also any event handler for initializing or updating the list.
original
If you modify the model value that you got passed in from the parent, then the parent also sees the change. Emitting the value as an event is probably redundant.
I guess you are modifying list (from <div *ngFor="let model of list">) in onEmit() which then causes *ngFor to rerender the list.
I don't think you should change #input property from within the component.
it suppose to listen and act to changes from the parent component.
MyComponent.ts
export class MyComponent{
#Input() model: Model;
//#Output() emitter: EventEmitter<Model> = new EventEmitter<Model>();
public constructor(private service: MyService){}
public toggle(): void {
this.service.send(model.id, model.name){
.subscribe(
result => this.onSuccess(result)),
error => this.onError(error),
() => this.onComplete());
}
public onSuccess(result: string): void {
if(result.inculdes("Some Text")) this.model.flag = true;
else this.model.flag = false;
//this.emitter.emit(this.model);
this.service.emitter.next(false);
}
public onError(error: any): void {
//notification using bootstrap-notify
}
public onComplete(): void {
//currently empty
}
}
Service
#Injectable // important
export class MyService{
public emitter: Subject<any> = new Subject();
public send(id: string, name: string){
return <Observable<string>>this.http
.post('url', new Dto(id, name))
.map(result => this.getData<string>(result))
.catch(this.catchBadResponse);
}
private getData<E>(result: Response): E {
//checking if result.status is ok
var body = result.json ? res.json(): null;
return <E>(body || {});
}
private catchBadRespomse: (error: any) => Observable<any> = (error: any) => {
var response = <Response>error;
var json = response.json();
var msg = json.Message;
var errormsg = json?
(json.error ? json.error: JSON.stringify(msg?msg:json)) :
(response.statusText || 'Error?');
return Obserable.of(errormsg);
}
}
Now you can listen to Service.emitter anywhere in app
Related
I am dealing with an error which when I try to create new page Object, it send to backend but it is not updating the array, I need to reload the page to see the all the array.
I am using Observable within async in the frontend.
I tried to console.log the ngOnInit of the page.component.ts but when I add new page and navigate to pages then the ngOnInit it isn't calling.
On Create new page it happens this.
It sends me to the route of pages where there I show all the list of pages.
But when I create new Page it is returningback an error which says.
ERROR Error: Error trying to diff 'Here is the name of the object'. Only arrays and iterables are allowed.
Update: as Marco said this happens because I mix page as Object instead I am iterating through array
But I am unable to resolve it and i need your help.
In the page.service.ts at pageModel when I add new Object it is returning me only the added Object not the whole array and there is the problem I think, but I don't know how to fix.
But If I reload page then I see all my Array.
This is my updated code.
This is my code.
export class PagesService {
public baseUrl = environment.backend;
private data = new ReplaySubject<any>();
public userID = this.authService.userID;
public editDataDetails: any = [];
public subject = new Subject<any>();
private messageSource = new BehaviorSubject(this.editDataDetails);
getPageID = this.messageSource.asObservable();
constructor(private http: HttpClient, private authService: AuthService) { }
public getPages() {
return this.http.get<any>(`${this.baseUrl}/pages/${this.userID}`).subscribe(res => this.data.next(res));
}
public pageModel(): Observable<Page[]> {
return this.data.asObservable(); // Here it throws error
}
public getPage(id): Observable<any> {
return this.http.get(`${this.baseUrl}/page/${id}`);
}
public setPage(page: Page, id: string) {
const api = `${this.baseUrl}/page`;
const user_id = id;
this.http.post<any>(api, page, {
headers: { user_id }
}).subscribe(res => this.data.next(res));
}
changeMessage(message: string) {
this.messageSource.next(message)
}
public updateDate(id: string, page: Page) {
const api = `${this.baseUrl}/page/${id}`;
return this.http.put<any>(api, page).subscribe(res => this.data.next(res.data));
}
Updated Code from Answer.
public updateDate(id: string, page: Page) {
const api = `${this.baseUrl}/page/${id}`;
return this.http.put<any>(api, page).subscribe(res => {
this.lastSetOfData = res;
this.data.next(this.lastSetOfData);
});
}
}
export class Page {
_id = "";
name = "";
slogan = "";
description = "";
url = "";
telephone: number;
pageUrl: string;
website: string;
founded: number;
organization: number;
email: string;
coverImage: string;
profileImage: string;
specialty?: Specialty[];
branches: Branches[];
locations?: Location[];
phone?:Phone;
userRole?: string;
roles?: Roles[];
}
export class Roles {
role= "";
userID = "";
}
This is the HTML of page.component .
<div class="main" *ngIf="!showWeb">
<div *ngFor="let page of pages$ | async" class="card width-900">
<app-pages-list class="d-flex width-900" [page]="page" [details]="'details'"></app-pages-list>
</div>
<div>
</div>
</div>
This is the TS file.
public pages$: Observable<Page[]>;
ngOnInit(): void {
this.pageService.getPages();
this.pages$ = this.pageService.pageModel();
}
And this is the code when I create new Page.
export class CreatePageComponent implements OnInit {
public page = new Page();
search;
public branch = [];
constructor(public router: Router,
public branchesService: BranchesService,
public authService: AuthService,
public pageService: PagesService,
public shareData: SenderService) { }
ngOnInit(): void {
}
createPage() {
this.page.url = this.page.name;
this.page.branches = this.branch;
this.page.locations = [];
this.page.specialty = [];
this.page.roles = [];
this.page.phone = this.page.phone;
this.page.pageUrl = `${this.page.name.replace(/\s/g, "")}${"-Page"}${Math.floor(Math.random() * 1000000000)}`;
this.pageService.setPage(this.page, this.authService.userID);
}
addBranch(event) {
this.branch.push(event);
this.search = "";
}
removeBranch(index) {
this.branch.splice(index, 1);
}
}
From my understanding of your code, your error is thrown because the data variable hold 2 types of objects.
In the PagesServices:
In getPages you give data a list of Page.
In setPage and updatePage you give data an instance of Page.
private data = new ReplaySubject<any>();
When you create a new page, data hold the last page you created (not an array). Then you try to iterate this page.
<div *ngFor="let page of pages$ | async"
This error come from the fact that you can't iterate a Page object.
You should stop using any so that this type of error occurs at compilation time, not at runtime. Also you need to store an instance of the array of page, add the item in your array after a post, and then replay the whole array.
Code
public updateDate(id: string, page: Page) {
const api = `${this.baseUrl}/page/${id}`;
return this.http.put<any>(api, page).subscribe((res) => {
const index: number = lastSetOfData.findIndex((_page: Page) => _page._id === res._id);
lastSetOfData[index] = res;
lastSetOfData = [...lastSetOfData];
this.data.next(lastSetOfData);
});
}
Also the updateDate function should be named updatePage.
The issue is the one identified in the response from #Marco. I elaborate starting from there.
There are several ways of fixing this problem. Probably the fastest is to add an instance variable lastSetOfData to PagesService where you hold the last version of the array. Then you initiatlize lastSetOfData in the getPages method. Finally in the setPage method you update lastSetOfData appending the Page returned by the service at the end of lastSetOfData and notify it using the ReplaySubject.
So the code could look like this
export class PagesService {
public baseUrl = environment.backend;
// specify the type of data notified by the ReplaySubject
private data = new ReplaySubject<Array<Page>>();
// define lastSetOfData as an array of Pages
private lastSetOfData: Array<Page> = [];
....
public getPages() {
return this.http.get<any>(`${this.baseUrl}/page/${this.userID}`).subscribe(res => {
// res should be an array of Pages which we use to initialize lastSetOfData
lastSetOfData = res;
this.data.next(lastSetOfData)
});
}
....
public setPage(page: Page, id: string) {
const api = `${this.baseUrl}/page`;
const user_id = id;
this.http.post<any>(api, page, {
headers: { user_id }
}).subscribe(res => {
// update lastSetOfData appending resp, which should be a Page
// not the use of the spread operator ... to create a new Array
lastSetOfData = [...lastSetOfData, resp];
// now you notify lastSetOfData
this.data.next(lastSetOfData)
});
}
// probably you have to modify in a similar way also the method updateTable
public updateDate(id: string, page: Page) {
....
}
....
....
}
Consider that this may be the fastest way to fix the problem. Check if it works and then you may want to try to refactor the code to look for a more rx-idiomatic solution. But my suggestion is first to see if this fixes the problem.
Problem is that you put an object in your replaysubject although an array is expected in other places.
next(myarray)
next(myobject)
This does not magically append an object to the array.
To do so, you'd need something like this:
data.pipe(take(1)).subscribe(list => {
list.push(newvalue);
data.next(list);
});
Basically you take the last value, a the new item, and push the new list.
I am having an issue with the ReplaySubject, I don't know what I have done wrong but the problem it is that when I change something and save it in backend, the ReplaySubject it calls new data but it is hiding them to show me see the picture.
I tried to use detectChanges but without any luck, but as i know the detectChanges will work only when we have parent -> child iterration.
This happens on update
This happens when I reload the page
If I remove the the this.data.next(res) at this line of the Put Request then it works but I need again to reload page to get new data.
return this.http.put(api, dataModel).subscribe(res => this.data.next(res));
This is the code of the service.
#Injectable({
providedIn: "root"
})
export class ModelDataService {
public baseUrl = environment.backend;
private data = new ReplaySubject<any>();
public userID = this.authService.userID;
constructor(private http: HttpClient, private authService: AuthService) {
}
public getJSON() {
return this.http.get(`${this.baseUrl}/data/${this.userID}`).subscribe(res => this.data.next(res));
}
public dataModel(): Observable<any> {
return this.data.asObservable();
}
public setData(data: Model) {
const api = `${this.baseUrl}/data`;
const user_id = this.authService.userID;
this.http.post(api, data, {
headers: {user_id}
}).subscribe(res => this.data.next(res));
}
public updateDate(id: string, dataModel: Model) {
const api = `${this.baseUrl}/data/${id}`;
return this.http.put(api, dataModel).subscribe(res => this.data.next(res));
}
}
This is the component.
public model$: Observable<Model>;
public model: Model;
constructor(
public authService: AuthService,
private modelDataService: ModelDataService,
public dialog: MatDialog,
public cd: ChangeDetectorRef) {
}
ngOnInit() {
this.authService.getUserProfile(this.userID).subscribe((res) => {
this.currentUser = res.msg;
});
this.modelDataService.getJSON();
this.model$ = this.modelDataService.dataModel();
this.model$.subscribe((data) => {
this.model = data; // here if i try to console log then I have the array but the page it will be blank
console.log(data);
});
}
And then for example I try to show data like this.
<ng-container class="Unit-unit-unitGroup" *ngFor="let personalData of model.personalData; let id = index">
</ng-container>
In the put Request I have added an console log and this is what I am getting.
But on reload I am getting I think another way of strucuter of data.
See picture
Use ChangeDetectorRef to detect changes again in the view when the data comes back.
this.model$.subscribe((data) => {
this.model = data;
this.cd.detectChanges();
});
<ng-container class="Unit-unit-unitGroup" *ngFor="let personalData of model.personalData; let id = index">
</ng-container>
this.model$.subscribe((data) => {
this.model = data; // here if i try to console log then I have the array but the page it will be blank
console.log(data);
});
public updateDate(id: string, dataModel: Model) {
const api = `${this.baseUrl}/data/${id}`;
return this.http.put(api, dataModel).subscribe(res => this.data.next(res));
}
You expect personalData to be a property of your model. However, as seen in the console log your res is an object including data as an object between. All you need to do is mapping res to it's data.
public updateDate(id: string, dataModel: Model) {
const api = `${this.baseUrl}/data/${id}`;
return this.http.put(api, dataModel).subscribe(res => this.data.next(res.data));
}
I need to run a method with 2 parameters, each parameter is gotten through some form of subscribe function. the first is the collection which is gotten through the url from angular's page routing. The second is the dokument, this is the firebase's firestore document.
export class FirebaseDocument implements OnInit {
collection: string;
dokument: any;
//== CONSTRUCTORS
constructor(
private route: ActivatedRoute,
private _db: AngularFirestore
) {}
//== Initialize
ngOnInit() {
console.log("__loading page component");
this.route.params.subscribe(params => {
this.collection = params["collection"];
});
console.log(this.collection);//collection populated correctly
//load the document from AngularFirestore
console.log("loading the document from firebase");
let itemsCollection = this._db.collection(url).valueChanges();
//subscribe to get the dok of the first document in the collection
itemsCollection.subscribe(docArr => {
this.dokument = docArr[0];
console.log(this.dokument);//dokument is populated
});
console.log(this.dokument);//dokument is undefined
this.doMultiParameterMethod(this.collection, this.dokument);
}
}
this.collection populates perfectly fine;
this.dokument is only populated inside the subscribe method
I need this to be populated by the time the next line is run. the console.log(this.dokument);
I have been dumbstruck by this because essentially the same code is used by the 2 subscribe methods but they don't behave the same way.
Sometimes a subscribe can be synchronous. This happens when the Observable is a ReplaySubject a BehaviorSubject or an Observable which has a shareReplay() pipe. (probably other options as well.
This will make the observable immediately fire on subscription. However, you should never count on this behavior, and always continue within your subscribe.. Or use pipes like mergeMap and create other observables which you can access in your template using the async pipe.
In your case. The this.route.params is obviously a 'replaying' Observable from which you get the latest value after subscribing. Otherwise you would have to wait for the params to change again until you get a value.
Your Database call cannot return an immediate response, because it's essentially a network request.
In your example code, you can update it to this, and use the async pipe in your template
export class FirebaseDocument implements OnInit {
readonly collection$: Observable<string> = this.route.params.pipe(
map((params) => params.collection)
);
readonly doc$: Observable<any[]> = this.db.collection(this.url).valueChanges().pipe(
shareReplay({ refCount: true, bufferSize: 1 })
);
constructor(private route: ActivatedRoute, private db: AngularFirestore) {}
ngOnInit() {
// don't forget to unsubscribe
combineLatest([
this.collection$,
this.doc$
]).subscribe((collection, document) => {
this.doMultiParameterMethod(collection, document);
});
}
}
Maybe you should make the Observable a Promise, in your case would be the following :
export class FirebaseDocument implements OnInit {
collection: string;
dokument: any;
//== CONSTRUCTORS
constructor(
private route: ActivatedRoute,
private _db: AngularFirestore
) {}
//== Initialize
ngOnInit() {
console.log("__loading page component");
this.route.params.subscribe(params => {
this.collection = params["collection"];
});
console.log(this.collection); //collection populated correctly
this.getDokument().then(docArr => {
this.dokument = docArr[0];
this.doMultiParameterMethod(this.collection, this.dokument);
});
}
getDokument(): Promise<any> {
let itemsCollection = this._db.collection(url).valueChanges();
return new Promise((resolve, reject) => {
itemsCollection.subscribe((response: any) => {
resolve(response);
}, reject);
});
}
}
I get an error that my this.worldCities is undefined and that I cannot apply find on it with the following code
export class SelectCityModalPage {
worldCities : Array<City>;
chosenCity:City;
myForm;
constructor(public navCtrl: NavController, public navParams: NavParams,
public appCitiesProvider:AppCitiesProvider, public viewCtrl:ViewController,
public formBuilder:FormBuilder) {
this.worldCities = this.appCitiesProvider.worldCities;
this.chosenCity = new City();
this.chosenCity.name = "";
console.log("In modal the world cities are " + this.worldCities);
this.myForm = formBuilder.group({
cityControl: ['Start typing...', this.checkIfValidCity]
//cityControl:['']
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad SelectCityModalPage');
}
closeModal(){
this.chosenCity = this.worldCities.find((element) =>{
return element.name == this.chosenCity.name;
});
this.viewCtrl.dismiss(this.chosenCity);
}
checkIfValidCity(control : FormControl){
let validation = this.worldCities.find((element) => {
return element.name == control.value;
});
return validation != undefined;
}
}
And my provider is like that :
export class AppCitiesProvider {
errorMessage;
worldCities:Array<City>;
constructor(public http: Http, errorHandler:ErrorHandler) {
console.log('Hello Cities Provider');
this.getWorldCities2()
.subscribe(
(cities) => {
this.worldCities = cities;
console.log("in provider the worldCities are " + this.worldCities);
},
(error: any) => this.errorMessage = <any>error);
;
}
getWorldCities2() {
return this.http.get('../assets/city.list.json')
.map(res => res.json());
}
}
What I don't understand is that the appCitiesProvider.worldCities is initialized when called on a previous page, so this should not be the issue.
Also when I don't have the formbuilder in the code, I don't have any issue. The issue is really appearing because of the checkIfValidCity function.
Do you know where that comes from and how to solve it ?
Thanks a lot!
Methods outside your constructor loses the context of the class, therefore using 'this' will mean the method and not necessarily the class. If you want your methods to use the context of the class you will need to bind it in your constructor.
Add
this.checkIfValidCity = this.checkIfValidCity.bind(this)
to your constructor.
I have a a function that returns an Observable<Person[]>, Person is my model:
export interface Person {
id: string;
age: number;
}
Now in my component.ts im calling this function and I want to retrieve that array so I can display it in the html.
the array that comes back example:
[{"id":"13434 1","age":21},{"id":"34334 1","age":27}]
I have 2 buttons that call the same function.
I have three methods in my component.ts that triggered when that buttons where clicked, and this is where I want to set some variable to hold the returned value of that Observable. I'v tried to do something but it didnt work...
this are the functions:
#Injectable()
export class MyCmp implements OnInit {
listOneData: Observable<Person[]>;
listTwoData: Observable<Animal[]>;
showListOne = false;
showListTwo = false;
constructor(private _myService: MyService) {
};
public showListOneData(): void {
this.showListOne = true;
this.showListTwo = false;
this._myService.getListOneData().subscribe(res => {
this.listOneData = res;
})
}
public showListTwo(): void {
this.showListTwo = true;
this.showListOne = false;
this._myService.getListTwoData().subscribe(res => {
this.listTwoData = res;
})
}
}
this.listTwoData = res; this line does not compile, its because im assigning Person[] to listOneData: Observable<Person[]>;, but even if I take of the Observable<> it dosent work.
Can someone please explain to me what woill be an efficiant way to do it? I dont want to do it async cause I want to send an array to the html, and base on the code where should I do unsubscribe?
thanks allot!
Sounds like you want two different things; data from the observable and a subscription object so you can unsubscribe:
#Injectable()
export class MyCmp implements OnInit {
listOneData: Person[];
listTwoData: Animal[];
listOneSubscription: Subscription;
listTwoSubscription: Subscription;
showListOne = false;
showListTwo = false;
constructor(private _myService: MyService) {
};
public showListOneData(): void {
this.listOneSubscription = this._myService.getListOneData().subscribe(res => {
this.showListOne = true;
this.showListTwo = false;
this.listOneData = res;
})
}
public showListTwo(): void {
this.listTwoSubscription = this._myService.getListTwoData().subscribe(res => {
this.showListTwo = true;
this.showListOne = false;
this.listTwoData = res;
})
}
}
Then, wherever you're wanting to unsubscribe:
this.listOneSubscription && this.listOneSubscription.unsubscribe();
this.listTwoSubscription && this.listTwoSubscription.unsubscribe();
You also mentioned you don't want to do it async; that doesn't make sense in JavaScript since this is asynchronous; ask yourself, what do you want to show to the user while the content is loading? You probably want to show some sort of progress indicator, so that should be built into your view.