Factory() Metodu ile Servis Oluşturmak

in #utopian-io7 years ago (edited)

Creating a Service with Factory () Method

We can refer to the services created by the factory () method, the factory service, or the factory service. The use of the factory () method can be seen as a function that returns a value, although its use is mostly similar to the service () method, but the service () method can be thought of as a constructor.

Factory() Metodu ile Servis Oluşturmak

factory() metodu ile oluşturulan servislere, factory servisi veya fabrike eden servis diyebiliriz. Kullanımı çoğunlukla service() metoduna benzeyen, fakat service() metodu bir kurucu olarak düşünülebilirken, factory() metodu belirlenen değeri dönen bir fonksiyon olarak değerlendirilebilir.

İsterseniz service() metodunu kullanarak oluşturduğumuz servis ile aynı işlemi yapan uygulamayı factory() metodu ile oluşturmayı gösterelim;

<!DOCTYPE html>
<html>
<head>
    <title>Angular JS Ders Uygulamaları</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
</head>
<body>

    <div ng-app="ngUygulamam" ng-controller="ngKontrol">

        <b>Sayı 1:</b> <input type="number" ng-model="sayi1"/><br>
        <b>Sayı 2:</b> <input type="number" ng-model="sayi2"/><br>
        <b>Sonuç:</b> {{sonuc}}<br/><br/>

        <button ng-click="toplaF()">Sayıları Topla</button>

    </div>

    <script type="text/javascript">

        var hesapServis = angular.module("ngHesapServis", []).factory("hesap", function(){

            var obj = {};
            obj.topla = function(s1, s2){

                return s1 + s2;

            };

            return obj;

        });

        var uygulama = angular.module("ngUygulamam", ["ngHesapServis"]);
        uygulama.controller("ngKontrol", function($scope, hesap){

            $scope.toplaF = function(){

                $scope.sonuc = hesap.topla($scope.sayi1, $scope.sayi2);

            };
            
        });

    </script>

</body>
</html>

AngularJS9.png

AngularJs-11.png

Örneğimizde gördüğünüz gibi, servisi taşıyan modül üzerinde factory metodu ile oluşturduğumuz hesap servisi içerisinde lokal olarak tanımladığımız obj değişkeni tekrar callback fonksiyonu ile dönüldü.

Not: Aslına bakılırsa, service metodu ile yapılabilecek her işlemin teorik olarak factory metodu tarafından da gerçekleştirilebileceği söylenilebilir. Ek olarak hangi kullanım durumlarında hangi servis oluşturma metodlarının kullanılabiıeceğini şu listede inceleyebilirsiniz;

http://demisx.github.io/angularjs/2014/09/14/angular-what-goes-where.html

Kendi oluşturduğunuz servisler içerisinde, AngularJS tarafından sunulan built-in servisleri de kullanabilirsiniz. $http ile gelen içerikteki yasaklı kelimeleri filtreleyen bir servis oluşturarak kullanımını örneğimizde gösterelim;

<!DOCTYPE html>
<html>
<head>
    <title>Angular JS Ders Uygulamaları</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
</head>
<body>

    <div ng-app="ngUygulamam" ng-controller="ngKontrol">
        
        {{icerik}}

    </div>

    <script type="text/javascript">

        var uygulama = angular.module("ngUygulamam", []);

        uygulama.controller("ngKontrol", function($scope, $http){

            $http.get("deneme.txt").then(function(resp){

                $scope.icerik = resp.data.replace("patates","***").replace("patates","***");

            });

        });

    </script>

</body>
</html>

AngularJS10.png

AngularJs-12.png

Bu kodumuzda servis kullanmadan, bu uygulamayı nasıl yazacağımızı gösterdik. Deneme.txt dosyası içeriğinde "Bu gün, ay sonra ilk defa patates ve üzerine biraz da patllcan yedim." bulunuyor ve bu text içerisindeki patates ve patlıcan kelimeıerini *** ile değiştirerek sansürledik.

Buna özel bir servis oluşturmak isteseydik şöyle olacaktı;

<!DOCTYPE html>
<html>
<head>
    <title>Angular JS Ders Uygulamaları</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
</head>
<body>

    <div ng-app="ngUygulamam" ng-controller="ngKontrol">
        
        {{icerik}}

    </div>

    <script type="text/javascript">

        var uygulama = angular.module("ngUygulamam", []);
        uygulama.service("yasakliFiltre", function($http){

            this.getYazi = function(dosyaYolu, callback) {

                var yazi;
                $http.get(dosyaYolu).then(function(response){

                    yazi = response.data.replace("patates", "***").replace("patlıcan", "***");
                    callback(yazi);

                });

            };

        });

        uygulama.controller("ngKontrol", function($scope, yasakliFiltre){

            yasakliFiltre.getYazi("deneme.txt", function(yazi){

            $scope.icerik = yazi;

        });

    });

    </script>

</body>
</html>

AngularJS11.png

AngularJs-13.png

Bu örneğimiz biraz karmaşık gibi görünüyor olabilir fakat, şimdiye kadar bahsetmediğimiz hiçbir şey bulunmuyor. Bu nedenle ayrıntılı bir şekilde incelersek nasll çalıştığım anlayabiliriz. Örnekte $http servisini kendi oluşturduğumuz yasaklıFiltre servisi içerisinde kullanıyoruz.

service() metodu ile oluşturduğumuz bu servis içerisinde, this objesi üzerinden kontrol metodunun kullanımına sunduğumuz bir fonksiyon olan getYazi() fonksiyonu ile, içeriği alınacak dosya yolu ve bir de callback fonksiyonu çağırıyoruz. Burada $http servisi ile içeriğini aldığımız dosyaYolu değişkeni yolunda bulunan dosyanın içerisindeki filtrelenecek kelimeleri *** ile değiştirip, yeni string değişkenini callback üzerinden gönderiyoruz.

Kontrol metodu içerisinde, tıpkı $http servisini kullandığımız gibi, dosyanın yolunu ve bir de callback fonksiyonu ile karşıdan gelen veriyi alarak sayfamızdaki expression yansımasına bağlı olan içerik değişkenine atıyoruz.

Not: Bir servis içinde, tıpkı bir kontrol metodunda kullandığımız gibi birden fazla servis de kullanabilir, hatta kendi oluşturduğumuz bir servisi, yine kendi oluşturduğumuz bir servis üzerinde de kuılanabiliriz.

Bir sonraki eğitimde görüşmek üzere...



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Hey @codings I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • This is your first accepted contribution here in Utopian. Welcome!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Coin Marketplace

STEEM 0.18
TRX 0.16
JST 0.030
BTC 62690.68
ETH 2463.17
USDT 1.00
SBD 2.62