Angular - Polymer Interaction

2019-06-20 07:32发布

问题:

I am planning to try a project in AngularJS in which all the components will be developed using Polymer. Now before starting this project, I have couple of queries:

  1. Can I update Polymer component data model (there by the UI too) after fetching data using Angular services? And if Yes, then if possible share an example.

  2. Can I call an Angular services for say, fetching data, from inside the Polymer component? (Say, I have a User Control as Polymer component for Validating user credential through Angular Services against MongoDB)?

    Please share an example if possible.

回答1:

There will be some complications with this setup.

The first is that Angular doesn't know how to bind to custom elements, so a binding from within Angular to a Polymer component like:

<my-element foo="{{ bar }}">

will set the foo attribute of the element, which can only be a string, but won't use Node.bind to setup a binding to the foo property. This is a big problem for binding complex objects, or for when you want a two-way binding.

I created a directive that allows you to use Node.bind from within Angular, but it's for Dart. You could port it to JS: https://github.com/google/angular_node_bind.dart

It works by capturing expressions in double square-braces and setting up a watch expression and a binding via Node.bind. The previous example would change to:

<my-element foo="[[ bar ]]">

The binding is two-way. If <my-element> changes the value of foo, the value of bar will be updated.

The second issue is dependency injection. Since the browser is responsible for creating custom element, Angular doesn't know when they are created and doesn't have a chance to inject dependencies. So you need a way for a Polymer element to get a hold of an Angular service (or any service object really, Angular or not).

Once you're using something like angular-node-bind you could use bindings to pass the service to the element. Maybe like this:

<my-element http-service="[[ $http ]]">

(Since I'm not really an Angular expert, I've just been trying to get Angular and Polymer to play together, I'm not 100% sure that $http is just available in expressions).

The Angular team has said that they intend to support custom elements in Angular 2.0, although their recent blog post doesn't mention it.



回答2:

Polymer elements are just regular elements. If you set properties on them, call methods on them, and listen to their events, there should be no complications using them with other frameworks or libraries. This is completely by design.

It may be tempting to cross-bind Angular and Polymer elements, but this is advanced and not strictly necessary. I would definitely advise against starting that way.