简体   繁体   English

如何在Angularjs中访问$ scope服务?

[英]How to access $scope in service in Angularjs?

I am currently trying to post tweet via using Twitter API directly from my website but I am new to Angular and having some issues regarding passing a parameter in the url. 我目前正在尝试直接使用Twitter API从我的网站上发布推文,但是我是Angular的新手,并且在通过url中传递参数时遇到了一些问题。 I want to pass status variable into the url becuase I'll be getting input from textarea. 我想将状态变量传递给url,因为我将从textarea获取输入。

service.js service.js

angular.module('twitterApp.services', [])
.factory('twitterService', function($q, $scope){
    var authorizationResult = false;

    return {
        initialize: function() {
            OAuth.initialize('#OAuth Key here', {cache: true});
            authorizationResult = OAuth.create('twitter');
        },
        isReady: function() {
            return(authorizationResult);
        },
        connectTwitter: function() {
            var deferred = $q.defer();
            OAuth.popup('twitter', {cache: true}, function(error, result){
               if(!error){
                   authorizationResult = result;
               } 
                else{
                    //Do Something else if there's an error
                }
                return deferred.promise;
            });
        },
        clearCache: function() {
            OAuth.clearCache('twitter');
            authorizationResult = false;
        },
        postTweet() {
            var status = $scope.textModel;
            var deferred = $q.defer();
            var promise = authorizationResult.post('/1.1/statuses/update.json?status=' + 'status').done(function(data){
                deferred.resolve(data);
            });
            return deferred.promise;
        }
    }
});

Here is my controller where I declared the variable, I am pretty sure that I am wrong but I need to know the solution for this. 这是我在其中声明变量的控制器,我敢肯定我错了,但是我需要知道解决方案。 Controller : 控制器

app.controller('TwitterController', function($scope, $q, twitterService) {

    $scope.textModel = "";

    twitterService.initialize();

    $scope.postTweet = function() {
        var status = $scope.textModel;
    }
});

index.html 的index.html

<!DOCTYPE html>
<html ng-app="twitterApp">
<head>
    <title>Twitter OAuth.io Example</title>
    <link rel="stylesheet" href="custom.css">
    <link rel="stylesheet" href="bootstrap.min.css">
    <script src="jquery-3.1.1.js"></script>
    <script src="bootstrap.min.js"></script>
    <script src="oauth.js"></script>
    <script src="angular.min.js"></script>
    <script src="app.js"></script>
    <script src="controller.js"></script>
    <script src="services.js"></script>
</head>
<body>
    <div class="container text-center" ng-controller="TwitterController">
        <h1>Tweet..</h1>
        <span><i>Or rather just do it more than classic version.</i></span>
        <div class="row">
            <div>
                <textarea placeholder="What's on your mind?" id="tweetBox" rows="10" ng-model="textModel"></textarea>
            </div>
        </div>
        <div>
            <button class="btn btn-lg" id="tweetButton" ng-click="postTweet()">Tweet</button>
        </div>
        <div>
            Your tweet will appear like this:
        </div>
        <div>
            " {{textModel}} "
        </div>
    </div>
</body>
</html>

You can pass an argument to your postTweet function. 您可以将参数传递给postTweet函数。

Part of your Service: 服务的一部分:

postTweet(text) {
        var status = text;
        var deferred = $q.defer();
        var promise = authorizationResult.post('/1.1/statuses/update.json?status=' + 'status').done(function(data){
            deferred.resolve(data);
        });
        return deferred.promise;
    }

And your Controller: 和您的控制器:

app.controller('TwitterController', function($scope, $q, twitterService) {

    $scope.textModel = "";

    twitterService.initialize();

   $scope.postTweet = function() {
       twitterService.postTweet($scope.textModel);
   }
});

Essentially the answer above is correct, I just want to add that it's important to handle the error in the service or at the very least in the controller, right now only deferred.resolve() is being called on success. 基本上以上答案是正确的,我只想补充一点,处理服务或至少控制器中的错误很重要,目前仅在成功时调用deferred.resolve()。 You should capture any twitter error and do a deferred.reject(err) So your controller looks like: 您应该捕获任何Twitter错误并执行deferred.reject(err),因此您的控制器如下所示:

$scope.postTweet = function() {
       twitterService.postTweet($scope.textModel)
       .then( data => console.log(data) )
       .catch( err => console.error(err) );
   }

I'm sure there are better ways to handle success/error than console.log but you get the idea I hope, don't forget the error case. 我确信比console.log有更好的方法来处理成功/错误,但是您可以理解,但不要忘记错误情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM