Angular - building a "public" function (newbie) - function

I'm After several days learning angularJS through converting my standart JS app to a ng one.
I was wondering about this simple scenario:
I have a global function called fb_connect(),
it can be used from any page (or any controller if you like) to make a facebook-based login.
This function makes a simple http call and receives a JSON object contain data to move on (display a pop up, login, etc...)
I read that I can define a Factory or a Service for my app and use it in any controller, which works fine.
So, I created a fb_connect factory function.
The problem is that now, in every page (every controller), I have to define that fb_connect in the constructor of every controller - for example :
function welcome($scope,fb_connect){});
What is the proper way to do this kind of actions using Angular without having to define these functions each and every time in every controller?
Thanks

Setting up factories and services is all part of the dependency injection system of Angular. Using that system is great when you need to create things that depend on other injected things. It's a big tree of dependencies. It's also nice for creating singletons, such that everywhere in your code end up using the same instance of some object.
It sounds to me like neither of these benefits apply in your case. I'd suggest just not using Angular's DI for it. You have some function defined globally, just call it directly and skip the DI. There's nothing wrong with that.
Of course you say it makes an Ajax call, so doesn't depend on the Angular $http service?

Your two options are:
Declare the function on the $rootScope
Inject it as a service
My advice is to go with making it a service. The whole purpose of services is explained in the Angular.js docs, just like this quote:
Angular services are singletons that carry out specific tasks common to web apps... To use an Angular service, you identify it as a dependency for the dependent (a controller, or another service) that depends on the service.
As you mentioned in your question, you'd prefer to not define the service in every controller you wish to use it in. With $rootScope you'll be injecting that also in every controller. So really it's a question of which you prefer, although to answer your question, the proper way of using a factory or service is to inject it into the controller you wish to use it in.

You can always put it in the $rootScope
myApp.run(function($rootScope, fb_connect){
$rootScope.welcome = function(){
};
});

Related

Angular2 functions

Does there exists a build in function that keeps on reloading the whole component until a boolean gets true. Bacause now before I can get some data I need to wait until a user has clicked a button in another component. But there is no relationship between those 2 components.
Does someone knows a way how to do this.
thx!
you can make use of Event Emitters in components to share information so that you need not wait for a user dependent action . Also make use of Service classes in order to pass information between components.
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
Also if you are getting information from a http call try and use observables or promises and then use ngIf or a elvus operator to get info into the component.
More on Angular Concepts https://rahulrsingh09.github.io/AngularConcepts/
I solved it by using a service where is create a subject/observable.
Check the link:
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
check the: Parent and children communicate via a service

Achieve Do after and before using ES6 Proxy

I've a View and Utility classes and wanted to hook-in the Utility method once View's job is done. So wanted to call the utility method (to add behavior to the view) once View's render call is done.
Using ES6 Proxy API, Is there a way to execute a method before / after executing the main method ? (aka method interceptions)
Similar to YUI3 Do API.
http://yuilibrary.com/yui/docs/api/classes/Do.html
Yes there is a way. Actually I'm trying to build the same thing and as long as you use a synchronous context I already got it working. Have a look at the code examples in the issue I created for my problem: stack overflow when returning an ES6 proxy through a promise
What you need to do to intercept the call is to use the ES6 proxy to get notified of the get-call that takes place to retrieve the function before the method is actually called.
In my example you can see that you get all the information about the call like what method was called with which parameters and also who called it and on which target it was originally called.

Resolving a dependency while supplying values for downstream dependencies

I've been running into endless problems attempting to use Windsor with Web API and injecting HttpRequestMessage into downstream dependencies of a controller. Since I've tried all the matching answers on Stackoverflow, I'd like to ask the question in a different way:
In Castle Windsor, how can I resolve a component instance while supplying a value for a downstream dependency? That is, the supplied value is required by a component that is required by the component being resolved.
For context, I'm trying to inject HttpRequestMessage so that I can use it to resolve the request context (primarily to resolve an absolute URL).
Edit I'd also like to point out that I don't currently have a dependency on Web Host / System.Web and I'd rather not change that.
A proper approach is to
Create IMyDesiredRouteParameterProvider
Implement it. Get the current request inside it and get the url
Register it and inject it in the desired dependent class via constructor.
I made myself such an implementation and I can say that this way it works fine. You can make Web.Infrastructure assembly and put the implementation there. Or put both the interface and the implementation there if you are going to reference it from another web module.
using System;
using System.Web;
namespace RouteParameterProvider
{
interface IMyRouteParameterProvider
{
string GetRouteParameter();
}
public class ControllerActionMethodRouteParameterProvider : IMyRouteParameterProvider
{
public string GetRouteParameter()
{
string Parameter = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"] as string;
if (string.IsNullOrEmpty(Parameter))
{
throw new InvalidOperationException();
}
return Parameter;
}
}
}
You can get every possible thing that the Request Context contains from :
HttpContext.Current.Request.RequestContext
And it will be better if you rethink your design decision :
I need HttpRequestMessage to be regstered prior to creating each
instance of SomethingController so that it will be available down at
the LinkGenerator layer.
Containers are to be initialized at runtime and then used to resolve.
I need HttpRequestMessage to be regstered prior to creating each
instance of SomethingController so that it will be available down at
the LinkGenerator layer.
It sounds like you want to register an item with the container at runtime, post-startup. In general, this is not a good practice--registration should be a discrete event that happens when the app is fired up, and the container's state should not be changed during runtime.
Dependency Injection is about resolving service components, not runtime state--state is generally passed via methods (method injection). In this case it sounds like your LinkGenerator component needs access to the ambient state of the request.
I'm not that familiar with HttpRequestMessage, but this answer seems to show that it is possible to retreive it from HttpContext.Current. You could make this a method on your LinkGenerator class, or wrap this call in a separate component that gets injected into LinkGenerator (HttpRequestMessageProvider?). The latter would be my preferred method, as it allows LinkGenerator to be more testable.
Given the lack of a clean way of doing this and Web API not providing information as to the hosted endpoint beyond per-request context objects, I ended up injecting the base url from configuration.
Is this library by Mark Seemann the answer? In the description he writes explicitly :
This approach enables the use of Dependency Injection (DI) because the
request can be injected into the services which require it.
Then gives an example :
// Inside an ApiController
var uri = this.Url.GetLink(a=> a.GetById(1337));
By which you can then pass the URL down the road in the service that you have injected in the controller.
UPDATE :
Mark Seemann wrote about the same exact problem here:
"Because HttpRequestMessage provides the context you may need to
compose dependency graphs, the best extensibility point is the
extensibility point which provides an HttpRequestMessage every time a
graph should be composed. This extensibility point is the
IHttpControllerActivator interface:..."
This way you can pass request context information to a component deep in the object graph by getting from the HttpRequestMessage and passing it to the DI container.
Just take a look at the interface of IHttpControllerActivator.
The WEB API framework gets the IHttpControllerActivator through DependencyResolver. You probably already replaced it by your CastleWindsorDependencyResolver. Now you have to implement and register your HttpControllerActivator and register it.
When the WEB API framework gets IHttpControllerActivator from DependencyResolver (your Castle Windsor DR) and calls IHttpControllerActivator.Create() it will pass you the HttpRequestMessage. You can get your info from there and pass it to the your CastleDR before you call Resolve(typeof(MyController)) which will resolve the whole object graph - that means you will have MyHttpContextInfo to inject in your XYZComponent deep in the resolution stack.
This way tou are passing the arguments in the last possible moment but it is still possible. In Castle Windsor I make such passing of arguments though CreationContext.AdditionalArguments["myArgument"];.

Call a controller inside a template and another controller in Fatfree framework

i'd like to know if i can call a controller action inside a template, and inside another controller in fatFree framework (F3).
I'm not sure if i understand you corrently, but calling a Class method in Template would go like this:
{{ MyConroller->doSomething() }}
Of cause you could call one controller within another too... just use raw php
$obj = new MyController();
$obj->foo();
or use the F3 call method $f3->call('MyController->doSomething');
Also check out the new API docs.
http://fatfreeframework.com/base#call
It's still under construction, but hopefully you'll find more information about this or any other framework part very soon.
Many MVC purists would balk at the idea of a View (template) calling methods on the Controller. They would say that the controller needs to provide the data that the view needs, or at least give it the Model, so that it can retrieve data from there.
Furthermore, the View probably shouldn't be doing anything (or asking another component to do anything), other than generating the display. But can query the Model for data. But maybe by doSomething() you do mean getSomeData().
While I'm not an MVC purist I do agree with the idea of keeping logic and functionality out of the view if at all possible.

Pass proxy to loaded module in a PureMVC MultiCore app?

I'm creating a flash campaign which will be loaded into a client's framework, which I have no control over. The framework will already have loaded a few things such as locale, fonts and copy, and will pass these things to my swf upon initialization.
Since the size of my swf (let's call it the shell) is restricted it will in turn display a campaign-specific preloader and then load another swf (let's call this the campaign) with the rest of the site.
The shell and the campaign will both be PureMVC modules. The shell will create a few proxies and populate these with data passed from the framework (locale constants, fonts etc), before loading in the campaign.
When the campaign is loaded it too will need locale and fonts etc. so my question is, what is the best way to pass this data along to the campaign module from the shell module?
I could create the same proxies in the campaign module and load the data again, which will be cached, but this obviously feels like the wrong way to go.
I've investigated the use of the pipes utility but this seems like a bit of an overkill in my case since the communication will be one-way and will just happen once during the initialization of the campaign.
Would it be "ok" from a design pattern point of view to pass the proxies to an init method of the campaign module and then register these proxies in the campaign module startup command? This seems wrong since these proxies have references to my shell application facade through notification names. Would it be ok if I move the notification names to some "NotificationConstants" class which both modules can use?
I could create similar proxies in the campaign module but this time populate them with the data objects from my old proxies passed to the previously mentioned init method? Spontaneously this feels like the best way to do it since the data objects don't have any references to my shell module but the "old" proxies do..
The solution I usually use is to create an interface:
interface Campaign {
function set campaignDetails(value:CampaignDetails):void;
//...
}
The campaign-module should implement this interface - in the implementation I recommend you to use a different proxy in the module, so that you would avoid having duplicated notifications and references.
When the shell is ready with the loading of the module it just has to:
if (module is Campaign)
{
(module as Campaign).campaignDetails = ...;
}
I'm sure I'm telling you nothing new. You just need to make sure to keep the acquaintance between the shell and the module only on an interface level. Then you just pass the data and leave the module MVC core to deal with it independently from the shell.