I'm currently trying to convert some good old $http Promises into rxJs observables in angular2.
A very simple example of something I used to do frequently in angular 1:
// Some Factory in Angular 1
var somethings = [];
var service = {
all: all
};
return service;
function all() {
return $http
.get('api/somethings')
.then(function(response) {
somethings = parseSomethings(response.data);
return somethings;
});
}
// Some Controller in Angular 1
var vm = this;
vm.somethings = [];
vm.loading = true;
loadThings();
function loadThings() {
SomeFactory
.all()
.then(function(somethings) {
vm.somethings = somethings;
})
.finally(function() {
vm.loading = false;
})
}
Now I can achieve something similar with angular2 using RxJs Observable and Subject. But I am unsure on how to return 'completion hooks' down to the caller. (E.g.: The loading in the angular1 controller)
What I tried with for angular2 is something similar:
// Some Service in Angular 2
export class SomeService {
private _somethings$: Subject<Something[]>;
private dataStore: {
somethings: Something[]
};
constructor(private http: Http) {}
get _somethings$() : Observable<Something[]> {
return this._somethings$.asObservable();
}
loadAll() {
this.http
.get(`api/somethings`)
.map(response => response.json())
.subscribe(
response => {
this.dataStore.somethings = parseSomethings(response.data);
this._somethings$.next(this.dataStore.somethings);
}
);
}
}
//Some Component in Angular 2
export class SomeComponent() {
constructor(private someService: SomeService) {}
ngOnInit() {
this.someService.loadAll();
this.somethings = this.someService.somethings$;
}
}
Note
I used a Subject / Observable here so that when I create / update / remove 'something' I can call .next to notify the subscribers.
E.g.:
create(something: Something) : Observable<Something>{
return this.http.post(`api/somethings`, JSON.stringify(something))
.map(response => response.json())
.do(
something => {
this.dataStore.somethings.push(something);
this._somethings$.next(this.dataStore.somethings); //Notify the subscribers
}
);
}
Note
Here I used .do in the method and when calling the method in a 'form component' I subscribe just to get completion handler:
this.someService.create(something).subscribe(
(ok) => ...
(error) => ...
() => stop loading indicator
)
Questions
How can we pass down a completion-hook to callers (e.g. angular 1 controller) in angular 2 with RxJs
What alternative paths do exist to achieve similar behaviour ?
Your last code example is fine. Just use map() instead of subscribe() and subscribe at call site.
You can use
return http.post(...).toPromise(val => ...))
or
return http.post(...).map(...).toPromise(val => ...))
to get the same behavior as in Angular where you can chain subsequent calls with .then(...)
Related
I have a redux-form with password field, trying to update the password word field with random number in this simple example. How to bind the 'this' to Axios catch function?
axios.get('https://www.random.org/integers/?num=1&min=1&max=20&col=1&base=10&format=plain&rnd=new').then(function(result) {
this.props.change('password', result.data);
})
.then(function(response) {
//
})
.catch(function(error) {
this.props.change('password', '999');
});
I know the above logic works fine because if I use an ES5 var this1 = this; and use this1 it works fine.
Regards!
Either you can use the method you've just described, i.e.
var $this = this
var func = function() {
$this.props.doSomething()
}
Or then you can bind the function to be executed with the right this context. In vanilla JS you can do it by using bind:
var func = function() {
this.props.doSomething()
}
// now this inside func will always be whatever it was here
func = func.bind(this)
In es6 binding this to anonymous functions has been simplified with arrow functions:
const func = () => {
// this will be always whatever it was where this func was defined
this.props.doSomething()
}
Hope this helps!
I have a angular service that wraps a server-sent events. How do I mock the server-sent events in unit testing? Can I use mockHttpbackend in this case?
My hack:
create a MockEventSource
class MockEventSource {
static lastInstance: MockEventSource;
constructor(url: string) {
MockEventSource.lastInstance = this;
}
onmessage: (message: any) => any;
}
register it on the window object
beforeEach(() => {
window["EventSource"] = MockEventSource;
MockEventSource.lastInstance = null;
});
and call onmessage on it:
MockEventSource.lastInstance.onmessage({ data: JSON.stringify(...) });
I have a project that uses angular's $http service to load data from a remote location. I want to use rxjs Observables so the call in my service looks like this:
userInfo() : Rx.Observable<IUserInfo> {
var url : string = someUrl + this._accessToken;
return Rx.Observable.fromPromise<IUserInfo>( this.$http.get<IUserInfo>( url ) );
}
and this is subscribed to by my controller like this:
getUserInfo() : void {
this._googleService.userInfo().subscribe(
( result ) => { this.handleUserInfo( result ) },
( fault : string ) => this.handleError( fault )
)
}
private handleUserInfo( result : IHttpPromiseCallbackArg<IUserInfo> ) : void {
console.log( "User info received at " + new Date() );
this._name = result.data.given_name + " " + result.data.family_name;
this._email = result.data.email;
this._profilePicUrl = result.data.picture;
}
the problem is that despite the name, email and profile pic being updated these changes are not visible. As soon as anything else triggers an angular $apply the changes appear but because of the Observable these changes in the controller happen after the angular digest loop that is triggered by the $http call.
This does work correctly if my service just returns a promise to the controller.
How do I update my view in this case? I do not want to manually have to wire up each observable to trigger a digest cycle. I want all Observables to trigger a digest cycle when they receive a new value or error.
We can use the ScopeScheduler from rx.angular.js for this. We only have to create a new one where we create our angular module and pass the $rootScope to it:
const module : ng.IModule = angular.module( 'moduleName', [] );
module.run( ["$rootScope", ( $rootScope ) => {
new Rx.ScopeScheduler( $rootScope );
}]);
That's all you have to do. Now all Rx.Observables trigger an $apply when they get a new value.
For some reason the ScopeScheduler was deleted when the rx.angular.js library was upgraded to rxjs version 4. We have to use rx.angular.js version 0.0.14 to use the ScopeScheduler.
I do not know what the suggested solution to this is in version 4.
A project using this fix can be viewed here:
https://github.com/Roaders/Typescript-OAuth-SPA/tree/observable_apply_issues
I couldn't get the Rx.ScopeScheduler method to work, so I just overwrote the rx observable subscribe method itself instead, and wrapped the callbacks in $rootScope.$apply :)
module.run(['$rootScope', 'rx', function ($rootScope, rx) {
rx.Observable.prototype.subscribe = function (n, e, c) {
if(typeof n === 'object') {
return this._subscribe(n);
}
var onNext = function(){};
if(n) {
onNext = function(value) {
if($rootScope.$$phase) {
n(value);
}
else {
$rootScope.$apply(function(){ n(value); });
}
};
}
var onError = function(err) { throw err; };
if(e) {
onError = function(error) {
if($rootScope.$$phase) {
e(error);
}
else {
$rootScope.$apply(function(){ e(error); });
}
};
}
var onCompleted = function(){};
if(c) {
onCompleted = function() {
if($rootScope.$$phase) {
c();
}
else {
$rootScope.$apply(function(){ c(); });
}
};
}
return this._subscribe(
new rx.AnonymousObserver(onNext, onError, onCompleted)
);
};
}]);
I have to implement some standard notification UI with angular js. My approach is the following (simplified):
<div ng-controller="MainCtrl">
<div>{{message}}</div>
<div ng-controller="PageCtrl">
<div ng-click="showMessage()"></div>
</div>
</div>
And with the page controller being:
module.controller("PageCtrl", function($scope){
counter = 1
$scope.showMessage = function(){
$scope.$parent.message = "new message #" + counter++;
};
});
This works fine. But I really don't like the fact that I need to call $scope.$parent.
Because if I am in another nested controller, I will have $scope.$parent.$parent, and this becomes quickly a nightmare to understand.
Is there another way to create this kind of global UI notification with angular?
Use events to send messages from one component to another. That way the components don't need to be related at all.
Send an event from one component:
app.controller('DivCtrl', function($scope, $rootScope) {
$scope.doSend = function(){
$rootScope.$broadcast('divButton:clicked', 'hello world via event');
}
});
and create a listener anywhere you like, e.g. in another component:
app.controller('MainCtrl', function($scope, $rootScope) {
$scope.$on('divButton:clicked', function(event, message){
alert(message);
})
});
I've created a working example for you at http://plnkr.co/edit/ywnwWXQtkKOCYNeMf0FJ?p=preview
You can also check the AngularJS docs about scopes to read more about the actual syntax.
This provides you with a clean and fast solution in just a few lines of code.
Regards,
Jurgen
You should check this:
An AngularJS component for easily creating notifications. Can also use HTML5 notifications.
https://github.com/phxdatasec/angular-notifications
After looking at this: What's the correct way to communicate between controllers in AngularJS? and then that: https://gist.github.com/floatingmonkey/3384419
I decided to use pubsub, here is my implementation:
Coffeescript:
module.factory "PubSub", ->
cache = {}
subscribe = (topic, callback) ->
cache[topic] = [] unless cache[topic]
cache[topic].push callback
[ topic, callback ]
unsubscribe = (topic, callback) ->
if cache[topic]
callbackCount = cache[topic].length
while callbackCount--
if cache[topic][callbackCount] is callback
cache[topic].splice callbackCount, 1
null
publish = (topic) ->
event = cache[topic]
if event and event.length>0
callbackCount = event.length
while callbackCount--
if event[callbackCount]
res = event[callbackCount].apply {}, Array.prototype.slice.call(arguments, 1)
# some pubsub enhancement: we can get notified when everything
# has been published by registering to topic+"_done"
publish topic+"_done"
res
subscribe: subscribe
unsubscribe: unsubscribe
publish: publish
Javascript:
module.factory("PubSub", function() {
var cache, publish, subscribe, unsubscribe;
cache = {};
subscribe = function(topic, callback) {
if (!cache[topic]) {
cache[topic] = [];
}
cache[topic].push(callback);
return [topic, callback];
};
unsubscribe = function(topic, callback) {
var callbackCount;
if (cache[topic]) {
callbackCount = cache[topic].length;
while (callbackCount--) {
if (cache[topic][callbackCount] === callback) {
cache[topic].splice(callbackCount, 1);
}
}
}
return null;
};
publish = function(topic) {
var callbackCount, event, res;
event = cache[topic];
if (event && event.length > 0) {
callbackCount = event.length;
while (callbackCount--) {
if (event[callbackCount]) {
res = event[callbackCount].apply({}, Array.prototype.slice.call(arguments, 1));
}
}
publish(topic + "_done");
return res;
}
};
return {
subscribe: subscribe,
unsubscribe: unsubscribe,
publish: publish
};
});
My suggestion is don't create a one on your own. Use existing models like toastr or something like below.
http://beletsky.net/ng-notifications-bar/
As suggested above, try to use external notifications library. There're a big variety of them:
http://alertifyjs.com/
https://notifyjs.com/
https://www.npmjs.com/package/awesome-notifications
http://codeseven.github.io/toastr/demo.html
What is the recommended way to connect to server data sources in AngularJS without using $resource.
The $resource has many limitations such as:
Not using proper futures
Not being flexible enough
There are cases when $resource may not be appropriate when talking to backend. This shows how to set up $resource like behavior without using resource.
angular.module('myApp').factory('Book', function($http) {
// Book is a class which we can use for retrieving and
// updating data on the server
var Book = function(data) {
angular.extend(this, data);
}
// a static method to retrieve Book by ID
Book.get = function(id) {
return $http.get('/Book/' + id).then(function(response) {
return new Book(response.data);
});
};
// an instance method to create a new Book
Book.prototype.create = function() {
var book = this;
return $http.post('/Book/', book).then(function(response) {
book.id = response.data.id;
return book;
});
}
return Book;
});
Then inside your controller you can:
var AppController = function(Book) {
// to create a Book
var book = new Book();
book.name = 'AngularJS in nutshell';
book.create();
// to retrieve a book
var bookPromise = Book.get(123);
bookPromise.then(function(b) {
book = b;
});
};
I recommend that you use $resource.
It may support (url override) in next version of Angularjs.
Then you will be able to code like this:
// need to register as a serviceName
$resource('/user/:userId', {userId:'#id'}, {
'customActionName': {
url:'/user/someURI'
method:'GET',
params: {
param1: '....',
param2: '....',
}
},
....
});
And return callbacks can be handled in ctrl scope like this.
// ctrl scope
serviceName.customActionName ({
paramName:'param',
...
},
function (resp) {
//handle return callback
},
function (error) {
//handler error callback
});
Probably you can handle code on higher abstraction level.