Using switchMap with Promises - javascript

I am learning Angular2, following the "Tour of Heroes" tutorial on Angular.io. Near the end of the tutorial, we set up routing to a detail page and pass a parameter indicating the hero to displace. This is handled using the params Observable in ActivatedRoute. We use switchMap to redirect from the params Observable to a Promise to return the data we actually want based on the parameter.
The syntax used in the tutorial is concise, so I tried to break it out into building blocks to get a better understanding of what is going on. Specifically, I have tried to replace right arrow notation with an actual function, that I think is identical. But my modification does not work.
Here is the code:
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id']))
//.switchMap(this.getHero)
.subscribe(hero => this.hero = hero);
}
getHero(params: Params) : Promise<Hero> {
return this.heroService.getHero(+params['id']);
}
What confuses me is why using the line that is currently commented out instead of the line above it, I get an error: "Cannot read property 'getHero' of undefined." The two versions of code look identical to me.

Fat-arrow function preserves the context of execution, allowing the this "variable" to be the same as in the parent scope. If you use .switchMap(this.getHero) then this will point to something else, not the component.
getHero(params: Params) : Promise<Hero> {
// "this" is not what you expect here
return this.heroService.getHero(+params['id']);
}
So this.heroService is undefined here.

You'd need to bind your getHero function.
.switchMap(this.getHero.bind(this))
Otherwise your change is identical. Using bind like this allows you to pass getHero as a standalone function to switchMap without losing what this means to it.
You can experiment with it:
'use strict';
const foo = {
bar: 'baz',
getBar: function() {
return this.bar;
}
};
foo.getBar();
// => 'baz'
const myGetBar = foo.getBar;
myGetBar();
// => TypeError: Cannot read property 'bar' of undefined
const boundGetBar = foo.getBar.bind(foo);
boundGetBar();
// => 'baz'
const otherObj = { bar: 'hi' };
const otherBoundGetBar = foo.getBar.bind(otherObj);
otherboundGetBar();
// => 'hi'
otherObj.getBar = myGetBar;
otherObj.getBar();
// => 'hi'

You cannot use this.getHero like in your snippet because
it's undefined (the service returns Observable that you have to subscribe before using its data)
it's not a property (doesn't have get modifyer).

Related

How do functions defined with => get called in Angular?

From here: https://angular.io/tutorial/toh-pt4 - hero.component.ts
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
I have understood that this heroes => this.heroes = heroes translates to as follows:
f( heroes )
{
return this.heroes = heroes;
}
Is return implied here?
I want to understand where from does this inner function get called. Who's calling it?
In the example code you provided,to return a list of heros, we have to write it like
getHeroes(): Hero[] {
this.heroService.getHeroes()
.subscribe(heroes => ({heroes : heroes}));
}
Above arrow function will translate to
f( heroes )
{
return this.heroes = heroes;
}
Otherwise, the code you provided, its just making an assignment to this.heros variable, so return statement does not apply, and the arrow function translate to
f( heroes )
{
this.heroes = heroes;
}
Further explanation of Arrow function
Arrow functions, like function expressions, can be used to return an object literal expression. The only caveat is that the body needs to be wrapped in parentheses, in order to distinguish between a block and an object (both of which use curly brackets).
Example
//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
return {
id: id,
name: name
};
};
// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });
console.log(setNameIdsEs6 (4, "Kyle")); // Object {id: 4, name: "Kyle"}
For a regular function, if the ‘this’ keyword were inside an object’s method (a function that belongs to an object), it would refer to the object. While in an arrow function, ‘this’, always references the owner of the function it is in. Adding a console.log(this) before the return in the arrow function returns a Window object.
Example
// ES5
const brunch = {
food: 'Dim sum',
beverage: 'Jasmine tea',
order: function() {
return `I'll have the ${this.food} with ${this.beverage} please.`
}
}
brunch.order(); //"I'll have the Dim sum with Jasmine tea please."
// ES6
const brunch = {
food: 'Dim sum',
beverage: 'Jasmine tea',
order: () => {
return `I'll have the ${this.food} with ${this.beverage} please.`
}
}
brunch.order(); //"I'll have the undefined with undefined please."
In the following arrow function heroes => this.heroes = heroes
Yes, return is implied, this may or may not be a problem depending on the rest of your code. I'm assuming in your case, you're not looking to return the assignment, you just want the assignment to happen.
So all you have to do is wrap the result in braces like so heroes => {this.heroes = heroes}, now nothing is returned.
As for your second question, who calls the inner arrow function: From the looks of your code, this.heroService.getHeroes() returns an observable. In your code you have "subscribed" to the observable. The easy way to think about is that the observable is telling your subscription to run the arrow function.
Basically, you are observing the observable. The observable needs time to think about it's response which is why you need to subscribe to it. When it is ready it will tell you it's response, and your arrow function inside the subscription is your response to the observable response. This is a very non-technical description to give you some intuition.
You should research observables/async functions to get a clear understanding.
this.heroService.getHeroes() returns a subscription object. In order to subscribe to it we should use .subscribe(heroes => this.heroes = heroes);.
subscribe maps the subscription object and extracts the data from the object and puts it in this.heroes, the first param inside the subscribe.
Then with the => operator we start writing actions like affectation, displaying, or anything to do, you can do anything after =>
in order to write more than one action you should use the braces like this:
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => { console.log('ur data from the observable',heroes);
this.heroes = heroes
});
}

Callback losing scope of containing function with angular

I have a segment of code where I am getting some weird output. The parameter being used in the function is changing when I would not think it would.
entry point to the code.
handleAction(action : HAction){
this.openForm("marksForm","Form");
}
method to open the form.
public openForm(name : string, type : string){
console.log("Name",name)
let cb = this.createComponentInitCallback(this.compService.getComponentType(type),
name);
let itemconfig ={
type: 'row',
content: [{
type: 'component',
title: 'Form Test',
componentName: 'h-form',
componentState: {}
}]
}
let tryRegister = false;
try{
this.goldenLayout.getComponent(name);
}catch(e){console.log("registering component",name); tryRegister=true;}
if(tryRegister)
this.goldenLayout.registerComponent(name,cb);
if(this.goldenLayout.root.contentItems[0])
this.goldenLayout.root.contentItems[ 0 ].addChild(itemconfig);
else
this.goldenLayout.root.addChild(itemconfig);
}
This method creates the defined callback function.
public createComponentInitCallback(componentType: Type<any>, name : string ): ComponentInitCallback {
console.log("1Name",name);
let f = (container: GoldenLayout.Container, componentState: any) => {
console.log("2Name",name);
this.ngZone.run(() => {
console.log("3Name",name);
// Create an instance of the angular component.
const factory = this.componentFactoryResolver.resolveComponentFactory(componentType);
const injector = this._createComponentInjector(container, componentState);
const componentRef = this.viewContainer.createComponent(factory, undefined, injector);
console.log("4Name",name)
componentRef.instance.name=name;
// Bind the new component to container's client DOM element.
container.getElement().append($(componentRef.location.nativeElement));
this._bindEventHooks(container, componentRef.instance);
// Store a ref to the compoenentRef in the container to support destruction later on.
(container as any)[COMPONENT_REF_KEY] = componentRef;
});
};
return f;
}
You will see my log statements. This callback gets executed inside the GoldenLayout library. However, I was pretty sure this should work.
Below are the outputs:
Name marksForm
1Name marksForm
2Name h-form
3Name h-form
4Name h-form
The first console output is logging what is passed into this method. You can see that it is obviously changing on me so I have to be doing something wrong. Oddly enough, the componentType parameter is working perfectly fine.
What am I doing wrong here?
A function that relies on lexical this and is supposed to be passed as callback should always be bound to the context.
createComponentInitCallback method can be bound to the context, either with bind or an arrow function (see this explanation on bound prototype methods vs arrow instance methods):
constructor() {
this.createComponentInitCallback = this.createComponentInitCallback.bind(this);
}
Or resulting callback can be bound to the context:
let cb = this.createComponentInitCallback(this.compService.getComponentType(type),
name).bind(this);
Considering there are no scenarios where this should differ from current class instance, the first option is preferable.
As for function scope, it cannot be lost under no circumstances. If name was passed as an argument in parent function, it will remain unchanged in nested function.
Unless you are using Angular HttpModule to make calls, any async call made with an external library will result in running your call back out of the original scope.
To mitigate this you need to assign this to a local variable the callback can use.
public createComponentInitCallback(componentType: Type<any>, name : string ): ComponentInitCallback {
console.log("1Name",name);
let self = this;
let f = (container: GoldenLayout.Container, componentState: any) => {
console.log("2Name",name);
this.ngZone.run(() => {
console.log("3Name",name);
// Create an instance of the angular component.
const factory = self.componentFactoryResolver.resolveComponentFactory(componentType);
const injector = self._createComponentInjector(container, componentState);
const componentRef = self.viewContainer.createComponent(factory, undefined, injector);
console.log("4Name",name)
componentRef.instance.name=name;
// Bind the new component to container's client DOM element.
container.getElement().append($(componentRef.location.nativeElement));
self._bindEventHooks(container, componentRef.instance);
// Store a ref to the compoenentRef in the container to support destruction later on.
(container as any)[COMPONENT_REF_KEY] = componentRef;
});
};
return f;
}

Why would you ever call .call() on Observable functions?

I am a relative beginner in Angular, and I am struggling to understand some source I am reading from the ng-bootstrap project. The source code can be found here.
I am very confused by the code in ngOnInit:
ngOnInit(): void {
const inputValues$ = _do.call(this._valueChanges, value => {
this._userInput = value;
if (this.editable) {
this._onChange(value);
}
});
const results$ = letProto.call(inputValues$, this.ngbTypeahead);
const processedResults$ = _do.call(results$, () => {
if (!this.editable) {
this._onChange(undefined);
}
});
const userInput$ = switchMap.call(this._resubscribeTypeahead, () => processedResults$);
this._subscription = this._subscribeToUserInput(userInput$);
}
What is the point of calling .call(...) on these Observable functions? What kind of behaviour is this trying to achieve? Is this a normal pattern?
I've done a lot of reading/watching about Observables (no pun intended) as part of my Angular education but I have never come across anything like this. Any explanation would be appreciated
My personal opinion is that they were using this for RxJS prior 5.5 which introduced lettable operators. The same style is used internally by Angular. For example: https://github.com/angular/angular/blob/master/packages/router/src/router_preloader.ts#L91.
The reason for this is that by default they would have to patch the Observable class with rxjs/add/operators/XXX. The disadvantage of this is that some 3rd party library is modifying a global object that might unexpectedly cause problems somewhere else in your app. See https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md#why.
You can see at the beginning of the file that they import each operator separately https://github.com/ng-bootstrap/ng-bootstrap/blob/master/src/typeahead/typeahead.ts#L22-L25.
So by using .call() they can use any operator and still avoid patching the Observable class.
To understand it, first you can have a look at the predefined JavaScript function method "call":
var person = {
firstName:"John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var myObject = {
firstName:"Mary",
lastName: "Doe",
}
person.fullName.call(myObject); // Will return "Mary Doe"
The reason of calling "call" is to invoke a function in object "person" and pass the context to it "myObject".
Similarly, the reason of this calling "call" below:
const inputValues$ = _do.call(this._valueChanges, value => {
this._userInput = value;
if (this.editable) {
this._onChange(value);
}
});
is providing the context "this._valueChanges", but also provide the function to be called base on that context, that is the second parameter, the anonymous function
value => {
this._userInput = value;
if (this.editable) {
this._onChange(value);
}
}
In the example that you're using:
this._valueChanges is the Input Event Observerable
The _do.call is for doing some side affects whenever the event input happens, then it returns a mirrored Observable of the source Observable (the event observable)
UPDATED
Example code: https://plnkr.co/edit/dJNRNI?p=preview
About the do calling:
You can call it on an Observable like this:
const source = Rx.Observable.of(1,2,3,4,5);
const example = source
.do(val => console.log(`BEFORE MAP: ${val}`))
.map(val => val + 10)
.do(val => console.log(`AFTER MAP: ${val}`));
const subscribe = example.subscribe(val => console.log(val));
In this case you don't have to pass the first parameter as the context "Observable".
But when you call it from its own place like you said, you need to pass the first parameter as the "Observable" that you want to call on. That's the different.
as #Fan Cheung mentioned, if you don't want to call it from its own place, you can do it like:
const inputValues$=this._valueChanges.do(value=>{
this._userInput = value;
if (this.editable) {
this._onChange(value);
}
})
I suppose
const inputValues$ = _do.call(this._valueChanges, value => {
this._userInput = value;
if (this.editable) {
this._onChange(value);
}
});
is equivalent to
const inputValues$=this._valueChanges.do(value=>{
this._userInput = value;
if (this.editable) {
this._onChange(value);
}
})
In my opinion it's not an usual pattern(I think it is the same pattern but written in different fashion) for working with observable. _do() in the code is being used as standalone function take a callback as argument and required to be binded to the scope of the source Observable
https://github.com/ReactiveX/rxjs/blob/master/src/operator/do.ts

TypeError: undefined is not an object when unit testing with jasmine

I'm trying to write a unit test for a function and I'm getting an error. I'm also unsure how to test other parts of the function correctly.
private dictionaryMap (loggedIn, response) {
const translations = this.convertToArrays(response.data.translations);
this.configureMomentLocale(language);
if (!loggedIn) {
this.cachePublicDictionary(translations);
}
// not testing this part
this.dictionary = new Dictionary({
translationMap: Object.assign({}, this.getPublicDictionaryFromCache() || {}, translations),
});
return this.rx.Observable.of(this.dictionary);
}
And my unit test so far looks like this:
describe('dictionaryMap', () => {
it('calls configureMomentLocale()', () => {
const foo = {
'foo':'bar',
};
spyOn(service, 'configureMomentLocale');
service.dictionaryMap({}, false);
expect(service.configureMomentLocale).toHaveBeenCalled();
});
});
And when I run this test I get this error:
TypeError: undefined is not an object (evaluating 'response.data.translationMap')
Do I need to mock response.data.translations or assign the json structure? (translationMap: {'email': 'email', 'forgotPassword': 'Forgot password?'})
Also, I'm not sure how to properly test the other parts of the function, like the if statement or returning the observable. I am new to unit testing.
Your method dictionaryMap accepts 2 parameters - 1st is loggedIn (presumably boolean) and the 2nd one is response. On the first line of that method (before calling configureMomentLocale) you have a line const translations = this.convertToArrays(response.data.translations); which expects the response variable to have a property named data.
In your test, you have 2 errors on the line service.dictionaryMap({}, false);:
You're setting the arguments in reverse order - you should put the boolean argument first and the object one second
The object doesn't have a property named data
The line should be corrected to be something similar to service.dictionaryMap(false, { data: {} });. You might even need to define translations property for data object - it really depends on what this.convertToArrays function does and how it handles undefined values.

understanding the code from transit.js

I was just going through the source of transit.js and came across the following fucntion ::
$.cssHooks['transit:transform'] = {
// The getter returns a `Transform` object.
get: function(elem) {
return $(elem).data('transform') || new Transform();
},
// The setter accepts a `Transform` object or a string.
set: function(elem, v) {
var value = v;
if (!(value instanceof Transform)) {
value = new Transform(value);
}
// We've seen the 3D version of Scale() not work in Chrome when the
// element being scaled extends outside of the viewport. Thus, we're
// forcing Chrome to not use the 3d transforms as well. Not sure if
// translate is affectede, but not risking it. Detection code from
// http://davidwalsh.name/detecting-google-chrome-javascript
if (support.transform === 'WebkitTransform' && !isChrome) {
elem.style[support.transform] = value.toString(true);
} else {
elem.style[support.transform] = value.toString();
}
$(elem).data('transform', value);
}
};
I understand the latter part of the function, but its really hard to understand the initial part of the function, the function can be found on git too , HERE .
Initially I see this, $.cssHooks['transit:transform'] what is that line really saying?
After that we have the below line of code I.E. the getter and setter method,
set: function(elem, v) {
But who is passing the elem and v inside the function, I don't see anything being passed?
Read about cssHooks at jQuery cssHooks
Look at the source code (search for hooks.get and hooks.set)
.cssHooks is an array of objects that contains getter and setters tha will be executed by .css(). Thats all.
$.cssHooks['transit:transform'] = {set: function(elem,value){}, get: function(elem){}}
equal:
$.cssHooks['transit:transform'] = {};
$.cssHooks['transit:transform'].set = function(elem, value){};
$.cssHooks['transit:transform'].get = function(elem){};
$(element).css('transit:transform',value)
comes to:
$.cssHooks['transit:transform'].set(element,value)
$(element).css('transit:transform')
comes to:
$.cssHooks['transit:transform'].get(element)
$.cssHooks['transit:transform'] = {set:function(){}, get: function(){} }
{...} is an object creation.get and set not executed at this moment.
They created {set:function(){}, get: function(){} }
So. Simply: .css() will execute set and get functions for hooked property.
If you want to know how real getters and setters works:
Object.defineProperty()
In Javascript, you can add/access to a property with this syntax :
myObject.myProperty
or with this syntax :
myObject['myProperty']
This is the same result
So your line
$.cssHooks['transit:transform']
just mean that we want to store an object (code between {} in your original post) inside the 'transit:transform' property which is inside the cssHooks property which is inside the $ object
This is the same things :
$['cssHooks']['transit:transform']
The reason why they use the [''] syntax is that transit:transform contains the ':' char which is not allowed if you want to access it this way :
$.cssHooks.transit:transform //doesn't work
EDIT:
To answer to your second question, i don't know...the code you are showing is just the 'description' of the "transit:transform' property

Categories