Angular使服务可以从任何地方访问

时间:2016-05-14 10:30:02

标签: javascript angularjs

我有服务用于检查我的用户是否可以查看我的应用程序中的内容。

我这样使用它:

<tab ng-controller="LibraryRTLController" ng-if="authFactory.hasFeature('ReadyToLearn')">

然而它似乎无法正常工作,因为我必须在每个似乎多余的控制器中初始化它。

所以我的问题是:在某种程度上我可以使用全球服务吗?

请注意,由于我无法在此解释的原因,我必须使用ng-if,因此属性指令对我没有帮助!

更新

所以我把它添加到我的运行功能中:

angular.module('app')
.run(function ($rootScope, AuthService, authFactory, $state) {
    $rootScope.authFactory = authFactory;
    $rootScope.$on('$stateChangeStart', function (event, next, toParams) {
        $state.newState = next;
        var authorizedRoles = next.data.authorizedRoles;
        if (!AuthService.isAuthorized(authorizedRoles)) {
            event.preventDefault();
            if (AuthService.isAuthenticated()) {
                // user is not allowed
            } else {
                // user is not logged in
                window.location.href = "http://" + window.location.hostname
            }
        }
    });
})

调试时,我能够看到它实际上是在正确设置变量。

在我的服务中,我创建了一个只发出警报的功能:

function doesWork ()
{
    alert('true!');
}

现在回到我的html中我有:

<tab ng-controller="LibraryRTLController" ng-init="authFactory.doesWork()">

然而没有任何结果?

2 个答案:

答案 0 :(得分:2)

  

在某种程度上,我可以在全球范围内使用服务吗?

您可以简单地将服务公开为$rootScope属性,以便它可以在每个模板中使用:

appModule.run(['$rootScope', 'authFactory', function($rootScope, authFactory) {
  $rootScope.authFactory = authFactory;
}]);

答案 1 :(得分:0)

是的,您可以通过引用注入依赖项的主根文件中的服务名称来全局访问服务

package com.angelnx.angelnx.mygcm.gcm;

import android.app.IntentService;
import android.content.Intent;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;


import com.angelnx.angelnx.mygcm.R;
import com.angelnx.angelnx.mygcm.app.Config;
import com.angelnx.angelnx.mygcm.app.EndPoints;
import com.angelnx.angelnx.mygcm.app.MyApplication;
import com.angelnx.angelnx.mygcm.model.User;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.gcm.GcmPubSub;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class GcmIntentService extends IntentService{

    private static final String TAG = GcmIntentService.class.getSimpleName();
    public GcmIntentService() {
        super(TAG);
    }
    public static final String KEY = "key";
    public static final String TOPIC = "topic";
    public static final String SUBSCRIBE = "subscribe";
    public static final String UNSUBSCRIBE = "unsubscribe";

    @Override
    protected void onHandleIntent(Intent intent) {
        String key = intent.getStringExtra(KEY);
        switch (key) {
            case SUBSCRIBE:
                // subscribe to a topic
                String topic = intent.getStringExtra(TOPIC);
                subscribeToTopic(topic);
                break;
            case UNSUBSCRIBE:
                break;
            default:
                // if key is specified, register with GCM
                registerGCM();
        }

    }
    private void registerGCM(){
        SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);

        try{
            InstanceID instanceID=InstanceID.getInstance(this);
            String token=instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE,null);
            Log.e(TAG,"GCM Registration Token:"+token);

            sendRegistrationToServer(token);
            sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER,true).apply();
        }
        catch (Exception e){
            Log.e(TAG,"FAILED TO COMPLETED TASK"+e);
            sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER,false).apply();
        }
        //Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }
    private void sendRegistrationToServer(final String token) {

        User user= MyApplication.getInstance().getPrefManager().getUser();

        if(user==null){
            return;
        }
        String endPoint= EndPoints.USER.replace("_ID_",user.getId());
        Log.e(TAG,"endpoints :"+endPoint);

        StringRequest strReq = new StringRequest(Request.Method.PUT,
                endPoint, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.e(TAG, "response: " + response);

                try {
                    JSONObject obj = new JSONObject(response);

                    // check for error
                    if (obj.getBoolean("error") == false) {
                        // broadcasting token sent to server
                        Intent registrationComplete = new Intent(Config.SENT_TOKEN_TO_SERVER);
                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(registrationComplete);
                    } else {
                        Toast.makeText(getApplicationContext(), "Unable to send gcm registration id to our sever. " + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    Log.e(TAG, "json parsing error: " + e.getMessage());
                    Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                NetworkResponse networkResponse = error.networkResponse;
                Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
                Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("gcm_registration_id", token);

                Log.e(TAG, "params: " + params.toString());
                return params;
            }
        };

        //Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(strReq);

    }
    /**
     * Subscribe to a topic
     */
    public static void subscribeToTopic(String topic) {
        GcmPubSub pubSub = GcmPubSub.getInstance(MyApplication.getInstance().getApplicationContext());
        InstanceID instanceID = InstanceID.getInstance(MyApplication.getInstance().getApplicationContext());
        String token = null;
        try {
            token = instanceID.getToken(MyApplication.getInstance().getApplicationContext().getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            if (token != null) {
                pubSub.subscribe(token, "/topics/" + topic, null);
                Log.e(TAG, "Subscribed to topic: " + topic);
            } else {
                Log.e(TAG, "error: gcm registration id is null");
            }
        } catch (IOException e) {
            Log.e(TAG, "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage());
            Toast.makeText(MyApplication.getInstance().getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    public void unsubscribeFromTopic(String topic) {
        GcmPubSub pubSub = GcmPubSub.getInstance(getApplicationContext());
        InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
        String token = null;
        try {
            token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            if (token != null) {
                pubSub.unsubscribe(token, "");
                Log.e(TAG, "Unsubscribed from topic: " + topic);
            } else {
                Log.e(TAG, "error: gcm registration id is null");
            }
        } catch (IOException e) {
            Log.e(TAG, "Topic unsubscribe error. Topic: " + topic + ", error: " + e.getMessage());
            Toast.makeText(getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}