<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Seyfettin TURAN on Medium]]></title>
        <description><![CDATA[Stories by Seyfettin TURAN on Medium]]></description>
        <link>https://medium.com/@seyfettinturan?source=rss-6b49d61bb6c7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Seyfettin TURAN on Medium</title>
            <link>https://medium.com/@seyfettinturan?source=rss-6b49d61bb6c7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 07:20:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seyfettinturan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[RxJS Kütüphanesi Nedir?]]></title>
            <link>https://medium.com/@seyfettinturan/rxjs-nedir-6be293349c95?source=rss-6b49d61bb6c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6be293349c95</guid>
            <dc:creator><![CDATA[Seyfettin TURAN]]></dc:creator>
            <pubDate>Sat, 10 Dec 2022 17:00:38 GMT</pubDate>
            <atom:updated>2022-12-11T19:35:55.930Z</atom:updated>
            <content:encoded><![CDATA[<p>Bu günlerin en yeni teknolojilerinden biri olan RxJs kütüphanesini sizlerle birlikte inceleyeceğiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2bTEmAP0HobdNJ58FZDew.jpeg" /></figure><p><a href="https://github.com/ReactiveX/rxjs"><strong>RxJS</strong></a>, gözlemlenebilir(observable) dizileri kullanarak eş zamansız tabanlı programlar oluşturmak için ve abone olunabilir(subscribable) nesnelere dönüştürdüğü eş zamansız programlar olay ve veri kaynakları üzerinde operatörler yardımıyla dönüşümler gerçekleştirebildiğimiz, gözlemleyenler(observer) aracılığıyla sonucu tüketebildiğiniz JavaScript’le yazılmış bir <strong>reaktif programlama</strong>(reactive programming) kütüphanesidir.</p><p><strong>RxJS’deki temel kavramlar şunlardır:</strong></p><p><strong>Observable;</strong> RxJs’in temel sınıfı konumundadır. Bilinen prosedürel programlamada olduğu gibi ardışık olarak işlenmiş kodsal süreçleri adım adım yerine getirip tepki göstermekten ziyade, olay bazlı duyarlılık sergilemektedir ve belli başlı olaylar cereyan ettiği zaman refleks göstermektedir. Somutlaştırıldığında (instantiate) gözlemlenebilir bir nesne döner. Herhangi bir veri veya olay Observable’a dönüştürülebilir. Observable’ın neyi ne zaman yayınlayacağını belirlemek için operatörler kullanılır. Bir Observable’dan başka bir Observable türetebilmek için yine operatörler kullanılmaktadır. Her Observable’da, akışı sonlandırmak için bir <strong>subscribe </strong>metodu bulunur.</p><p><strong>Observer;</strong> Observable tarafından sağlanan değerlerin nasıl dinleneceğini bilen bir geri arama koleksiyonudur. Observable’ın yayınladığı uyarı ve değerleri sonlandırmaya yarar. Observer kullanımında üç farklı tip çağrılabilir:</p><ul><li>Veriyi kullanmak için <strong>next</strong></li><li>Hata işlemek için <strong>error</strong></li><li>Observable’ın işinin bittiği durum için <strong>complete</strong></li></ul><p><strong>Subscription(Abonelik);</strong> bir Observable yürütülmesini temsil eder, öncelikle yürütmeyi iptal etmek için kullanışlıdır. Yani bir Observable’a abone olduğunuzda dönen nesne. Her <strong>subscriptio </strong>olduğunda onu sonlandıran bir <strong>unsubscribe</strong> metodu bulunur. Subscription sonlandığı zaman Observable yok olmaz; sadece kaynak tüketmeyi bırakır. Ama Observable sonlandığı zaman Observable’a olan tüm subscription’lar kendiliğinden sonlanır.</p><p><strong>Subject; </strong>EventEmitter’a eşdeğerdir ve bir değeri veya olayı birden çok Observers, yani çok noktaya yayınlamanın tek yoludur. Hem Observable gibi abone olunabilen, hem de Observer’daki tüm metotları yani <strong>next</strong>, <strong>error </strong>ve <strong>complete </strong>metotlarını barındıran bir sınıf konumundadır. Değer yayınlamaya olanak tanır. Hatalı kullanıma elverişlidir.</p><p><strong>Schedulers; </strong>eşzamanlılığı kontrol etmek için merkezileştirilmiş dağıtıcılardır. Örneğin başka bir yerde hesaplama gerçekleştiğinde koordinasyon sağlamamıza olanak tanır.</p><p><strong>Pipe; </strong>pipe fonksiyonu, Observable veri kaynağınızdaki operatörleri kullanan bir birleştirme hattıdır. Süreçli bir üretim bandı da diyebiliriz. Verilerde, isteğe göre filtreleme ve dönüştürme işlemleri yapılabilir.</p><h4><strong>RxJS Operatörler</strong></h4><p>Operatörler, bir kayaktan gelen değerleri kontrol etmemize ve dönüştürülmesine yardımcı olurlar ve dönüştürülen değerlerin <strong>Observable </strong>değerini döndürürler. İşlevsel bir programlama tarzı sağlayan saf işlevlerdir.</p><p><strong>of ();</strong> bu operatör iletilen bağımsız değişkenleri alır ve bunları gözlemlenebilir hale getirir.</p><pre>import express from &quot;express&quot;;<br>import { of } from &quot;rxjs&quot;;<br><br>const opof = express.Router();<br><br>opof.route(&quot;/opof&quot;).get(async (req, res, next) =&gt; {<br>  //with opretor of You can create a sequence which consist of some variables which you choosed<br>  const source = of(1, &quot;mike&quot;, true, 4, { country: &quot;German&quot; });<br>  const subscribe = source.subscribe(console.log);<br>});<br><br>module.exports = opof;</pre><p><strong>interval(); b</strong>u operatör, verilen süre için her zaman için bir Observable oluşturur.</p><pre>import express from &quot;express&quot;;<br>import { interval } from &quot;rxjs&quot;;<br><br>const opinterval = express.Router();<br><br>opinterval.route(&quot;/opinterval&quot;).get(async (req, res, next) =&gt; {<br>  //emit value in sequence every 1 second<br>  const source = interval(1000).subscribe((val) =&gt; console.log(val));<br>});<br><br>module.exports = opinterval;</pre><p><strong>timer();</strong> bu operatör, zaman aşımından sonra değeri yayınlayacak bir Observable oluşturacak ve değer her çağrıdan sonra artmaya devam edecektir.</p><pre>import express from &quot;express&quot;;<br>import { timer, of } from &quot;rxjs&quot;;<br>import { concatMapTo } from &quot;rxjs/operators&quot;;<br><br>const optimer = express.Router();<br><br>optimer.route(&quot;/optimer&quot;).get(async (req, res, next) =&gt; {<br>  //example - 1;<br>  const source = timer(1000);<br>  //output: 0<br>  const subscribe = source.subscribe((val) =&gt; console.log(&quot;example-1: &quot; + val));<br><br>  //example-2<br>  const source2 = timer(1000, 2000);<br>  //output: 0,1,2,3,4,5......<br>  const subscribe2 = source2.subscribe((val) =&gt;<br>    console.log(&quot;example-2: &quot; + val)<br>  );<br><br>  // example-3<br>  // This could be any observable<br>  const source3 = of(1, 2, 3);<br><br>  const result = timer(3000)<br>    .pipe(concatMapTo(source3))<br>    .subscribe((x) =&gt; console.log(&quot;example-3:&quot; + x));<br>});<br><br>module.exports = optimer;</pre><p><strong>from ();</strong> bir Observable nesne içerisine <strong>array</strong>, <strong>promise </strong>veya <strong>iterable </strong>değerler eklemek için kullanılır. Kısaca bir diziden Observable, dizi benzeri bir nesne, söz, yinelenebilir bir nesne veya gözlemlenebilir benzeri bir nesne oluşturmaktır.</p><pre>import express from &quot;express&quot;;<br>import axios from &quot;axios&quot;;<br>import { from } from &quot;rxjs&quot;;<br><br>const opfrom = express.Router();<br><br>opfrom.route(&quot;/opfrom&quot;).get(async (req, res, next) =&gt; {<br>  await axios.get(&quot;https://swapi.dev/api/people&quot;).then((result) =&gt; {<br>    const array = from(result.data.results);<br>    array.subscribe(console.log);<br>  });<br>});<br><br>module.exports = opfrom;</pre><p><strong>filter(); b</strong>u operatör, verilen yüklem işlevine dayalı olarak Observable kaynaktan gelen değerleri filtrelemektedir.</p><pre>import express from &quot;express&quot;;<br>import axios from &quot;axios&quot;;<br>import { from } from &quot;rxjs&quot;;<br>import { filter } from &quot;rxjs/operators&quot;;<br><br>const opfilter = express.Router();<br><br>opfilter.route(&quot;/opfilter&quot;).get(async (req, res, next) =&gt; {<br>  await axios.get(&quot;https://swapi.dev/api/people&quot;).then((result) =&gt; {<br>    const array = from(result.data.results);<br>    array<br>      .pipe(filter((val) =&gt; parseInt(val[&quot;height&quot;]) &gt; 100))<br>      .subscribe((val) =&gt; console.log(&quot;height: &quot; + parseInt(val[&quot;height&quot;])));<br>  });<br>});<br><br>module.exports = opfilter;</pre><p><strong>concat(); </strong>birden fazla Observable nesnesini bir dizi elemanı gibi sıraya dizer ve sırayla çalıştırır. Biri bitmeden diğerine geçmez. Bunu, biri bitmeden diğeri başlayamayan işlem sıralaması olarak düşünebiliriz.</p><pre>import express from &quot;express&quot;;<br>import { of } from &quot;rxjs&quot;;<br>import { concatMap, delay } from &quot;rxjs/operators&quot;;<br><br>const opconcatmap = express.Router();<br><br>opconcatmap.route(&quot;/opconcatmap&quot;).get(async (req, res, next) =&gt; {<br>  // If order is important at getting data from source then concatMap is usefull<br>  const source = of(3000, 2000, 1000)<br>    .pipe(concatMap((val) =&gt; of(`Delayed by: ${val}ms`).pipe(delay(val))))<br>    .subscribe((val) =&gt; console.log(`With concatMap: ${val}`));<br>});<br><br>module.exports = opconcatmap;</pre><p><strong>forkJoin(); </strong>tüm Observable’lar tamamlanana kadar bana haber verme, sonra bana tüm değerleri bir kerede ver.</p><p><strong>merge();</strong> concat işleminin benzeri olan bu operatörde, birden fazla Observable nesnesini bir dizi elemanı gibi sıraya dizer ancak işlemlerin sırayla yapılması beklenmez.</p><pre>import express from &quot;express&quot;;<br>import { of } from &quot;rxjs&quot;;<br>import { delay, mergeMap } from &quot;rxjs/operators&quot;;<br><br>const opmergemap = express.Router();<br><br>opmergemap.route(&quot;/opmergemap&quot;).get(async (req, res, next) =&gt; {<br>  // mergeMap handles the data without order unlike concatMap, in this case mergeMap result inner subscription without to wait previous datas ends And does it so fast<br>  const source = of(3000, 2000, 1000)<br>    .pipe(mergeMap((val) =&gt; of(`Delayed by: ${val}ms`).pipe(delay(val))))<br>    .subscribe((val) =&gt; console.log(`With mergeMap: ${val}`));<br>});<br><br>module.exports = opmergemap;</pre><p><strong>map(); </strong>Observer verilerde değişiklik yapmak için kullanılabilir.</p><pre>import express from &quot;express&quot;;<br>import axios from &quot;axios&quot;;<br>import { from } from &quot;rxjs&quot;;<br>import { map } from &quot;rxjs/operators&quot;;<br><br>const opMap = express.Router();<br><br>opMap.route(&quot;/opmap&quot;).get(async (req, res, next) =&gt; {<br>  await axios.get(&quot;https://swapi.dev/api/people&quot;).then((result) =&gt; {<br>    const array = from(result.data.results);<br><br>    array<br>      .pipe(map((val) =&gt; parseInt(val[&quot;height&quot;]) + 50))<br>      .subscribe(console.log);<br>  });<br>});<br><br>module.exports = opMap;</pre><p><strong>switchMap; </strong>mergeMap gibi, ancak Observable kaynak yaydığında, iç Observable’ın önceki tüm aboneliklerini iptal edin.</p><pre>import express from &quot;express&quot;;<br>import { of } from &quot;rxjs&quot;;<br>import { map, switchMap } from &quot;rxjs/operators&quot;;<br><br>const opswitchmap = express.Router();<br><br>opswitchmap.route(&quot;/opswitchmap&quot;).get(async (res, req, next) =&gt; {<br>  let obs = of(1, 2, 3, 4);<br><br>  //Using MAP<br>  obs<br>    .pipe(<br>      map((val) =&gt; {<br>        return val * 2; //Returning Value<br>      })<br>    )<br>    .subscribe((ret) =&gt; {<br>      console.log(&quot;Recd from map : &quot; + ret);<br>    });<br><br>  // Using SWITCHMAP<br>  obs<br>    .pipe(<br>      switchMap((val) =&gt; {<br>        return of(val * 2); //Returning Value<br>      })<br>    )<br>    .subscribe((ret) =&gt; {<br>      console.log(&quot;Recd from map : &quot; + ret);<br>    });<br>});<br><br>module.exports = opswitchmap;</pre><p>Kısaca özetlemek gerekirse:</p><p>Bir youtube kanalında dinlenilen veri kaynağına <strong>subject, </strong>kanalı takip eden kişiye <strong>Observer</strong>, kanala abone olma işlemine subscribe denir. Observable ise kanalın zaman içerisinde video yayınlamasını temsil eder.</p><p>Bu güzel yazımızda bizimle birlikte olduğunuz için teşekkürler. Öğrenmek sonu gelmeyen bir bilgi edinme’dir. Bilgilerinizin artması dileğiyle. Hoşça kalın:)</p><h4>KAYNAKLAR</h4><ul><li><a href="https://rxjs.dev/">RxJS</a></li><li><a href="https://www.armanozak.com/">ArmanOzak.com | JavaScript Blogu | Levent Arman Özak</a></li><li><a href="https://www.tutorialspoint.com/rxjs/rxjs_operators.htm">RxJS - Operators</a></li><li><a href="https://thrkardak.medium.com/rxjs-yak%C4%B1ndan-bak%C4%B1%C5%9F-1-observables-807c59d3dad9">RxJS’e yakından bakış -1: Observables</a></li><li><a href="https://medium.com/@omakemircan/angular-rxjs-k%C3%BCt%C3%BCphanesi-nedir-dccaba21fff6">Angular RxJS Kütüphanesi nedir ?</a></li><li><a href="https://www.bayramucuncu.com/rxjs-operatorler/">RxJS Operatorler | Bayram Üçüncü</a></li><li><a href="https://netbasal.com/rxjs-six-operators-that-you-must-know-5ed3b6e238a0">RxJS — Six Operators That you Must Know</a></li><li><a href="https://www.gencayyildiz.com/blog/angular-4-observable-ile-asenkron-http-service-islemleri/">Angular 4 - Observable İle Asenkron Http Service İşlemleri</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6be293349c95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NgRx Kütüphanesi Nedir?]]></title>
            <link>https://medium.com/@seyfettinturan/ngrx-k%C3%BCt%C3%BCphanesi-nedir-946ca07cfe37?source=rss-6b49d61bb6c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/946ca07cfe37</guid>
            <dc:creator><![CDATA[Seyfettin TURAN]]></dc:creator>
            <pubDate>Sat, 10 Dec 2022 07:55:26 GMT</pubDate>
            <atom:updated>2022-12-11T19:34:53.948Z</atom:updated>
            <content:encoded><![CDATA[<p>Bu günlerin en yeni teknolojilerinden biri olan NgRx kütüphanesini sizlerle birlikte inceleyeceğiz. Bunun için öncelikle <strong>State’in</strong>, <strong>State Management</strong>’ın, <strong>Redux</strong>’ın ve <strong>Store</strong>’ın ne olduğuna bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bV2sXt_IYwlHm7Oo.png" /></figure><p>NgRx, angular’da reactive web uygulamaları oluşturmak için kullanılan bir kütüphane’dir. Redux Pattern’i benimsemiş ve RxJS kütüphanesiyle desteklenmiş olan Angular’a özel State Management çözümleri için geliştirilmiş bir kütüphanedir. NgRx, farklı bileşenler arasında veri paylaşımı yapmamıza olanak tanımakla birlikte verilerin yeniden kullanımı için küresel bir durum oluşturur. Diğer bir deyişle state’i tek bir yerden etkili bir şekilde yönetmenizi sağlayan bir araçtır. O zaman gelin öncelikle <strong>state’</strong>in daha sonra da <strong>State Management</strong>’ın ve son olarak <strong>Redux</strong>’ın ne olduğuna kısaca bakalım.</p><p><strong>State;</strong> herhangi bir uygulamanın tüm belleğidir. Bir başka deyişle uygulama sürecindeki herhangi bir veri o anki state’dir.</p><p><strong>State Management;</strong> stateler’in farklı noktalar üzerindeki anlık değişimlerinin oluşması’dır.</p><p><strong>Redux;</strong> Angular gibi JavaScript temelli uygulamalarda State Management süreçlerini basitleştirmek için kullanılan pattern’dır. Redux tek bir store’dan beslenmekte ve tüm component’lere o store üzerinden veri sağlamaktadır. Redux’un kullanılmadığı durumlarda ise bir karmaşa davranış sergilenmektedir. Redux pattern View’de herhangi bir state değişikliği söz konusu olduğunda bu değişikliği temsil eden bir action fırlatılmakta ve fırlatılan bu action’ı reducer fonksiyonu ile yakalayarak yapılan değişiklik algılanmakta ve store’da ki mevcut state yerine gerekli güncellemelerin yapıldığı yeni state oluşturularak, store’a gönderilmektedir. Bu işlem neticesinde, store’da yenilenen state verisi ilgili tüm view’ler tarafından güncellenmiş olacaktır.</p><h4>Store</h4><p>Elimizdeki bilgileri saklamamıza yarar. Yani state’in tutulduğu yapılardır.</p><p><strong>Örneğin; </strong>bir uygulamanın kullanıcı bilgilerini veya uygulama hakkındaki diğer bilgileri kendisinde saklar.</p><p>En önemli noktalarından biri <strong>store “</strong>immutable”dir. Bu alana yazılan değerler değiştirilemez. Store’ın üç temel parçası bulunmaktadır. Bunlar aşağıda verilmiştir.</p><p><strong>Action; </strong>state üzerinde yapılacak işlemleri ifade eder. Bu işlemleri isimlendirirken uniq(benzersiz) isimler kullanılmalıdır. Service’den veya component’ten tetikleme yapılabilir.</p><pre><br>import { createAction } from &#39;@ngrx/store&#39;;<br><br>export const increment = createAction(&#39;[Counter Component] Increment&#39;);<br>export const decrement = createAction(&#39;[Counter Component] Decrement&#39;);<br>export const reset = createAction(&#39;[Counter Component] Reset&#39;);</pre><p><strong>Reducer;</strong> var olan state’i değiştirerek yeni bir state oluşturmamıza olanak tanır. State üzerinde yapılabilecek işlemler, methodlar burada yapılır. Methodları “<strong>on</strong>” içerisine yazılır. Birinci parametre, tetiklendiğinde hangi Action’ ın çalışacağı; ikinci parametre’ ye ise method yazılır ve bu method ile birlikte yeni bir state uluştururuz.</p><pre>const _counterReducer = createReducer(<br>  initialState,<br>  on(increment, (state) =&gt; state + 1),<br>  on(decrement, (state) =&gt; state - 1),<br>  on(reset, (state) =&gt; 0)<br>);</pre><p><strong>Selector;</strong> elimizdeki stateler’den hangi state’i seçeceğimiz yazılır.</p><p><strong>Props;</strong> kullanıcıdan gelecek olan veriyi temsil eder. Herhangi bir veri işlenmeyecekse kullanmayabilirsiniz</p><p>Konuyu teoride daha da netleştirebilmek için aşağıdaki hareketli görseli inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LPI3-FWXlaOkRW0V.gif" /></figure><p>Şemadan görüldüğü üzere, UI’da(yani view’de) herhangi bir state değişikliği söz konusu olduğunda bu değişikliği temsil eden bir action fırlatılmakta ve fırlatılan bu action’ı reducer fonksiyonu ile yakalayarak yapılan değişiklik algılanmakta ve store’da ki mevcut state yerine gerekli güncellemelerin yapıldığı yeni state oluşturularak, store’a gönderilmektedir. Bu işlem neticesinde, store’da yenilenen state verisi ilgili tüm view’ler tarafından güncellenmiş olur.</p><p>Gelin bu konuyu uygulayarak anlamaya çalışalım. Öncelikle projemize ngRx’i dahil edelim. Bir kitap ekleme ve silme uygulaması yapmak için bir proje oluşturalım. daha sonra aşağıdaki kodu projemize uygulayalım.</p><pre>npm install @ngrx/store</pre><p>İlk olarak actionlarımızı yazarak başlayalım. Bunun için state/app.actions.ts dosyamı açıyorum.</p><pre>import { createAction, props } from &#39;@ngrx/store&#39;;<br>import { BookModel } from &#39;../models/bookModel&#39;;<br><br>export const loadBooks = createAction(<br>  &#39;[Book] Load&#39;<br>);<br><br>export const addBook = createAction(<br>  &#39;[Book] Add&#39;,<br>  props&lt;{book: BookModel}&gt;()<br>)<br><br>export const deleteBook = createAction(<br>  &#39;[Book] Delete&#39;,<br>  props&lt;{id:number}&gt;()<br>)<br>export const selectBookById = createAction(<br>  &#39;[Book] Select Book&#39;,<br>  props&lt;{bookId: number}&gt;()<br>)</pre><p>Dikkat ederseniz props ile action tetiklendiğinde ihtiyacı olacak veriyi belirtiyorum.</p><p>Şimdi state/app.reducer.ts dosyamızı hazırlayalım.</p><pre>import { createReducer, on } from &#39;@ngrx/store&#39;;<br>import { BookModel } from &#39;../models/bookModel&#39;;<br>import * as AppActions from &#39;./app.actions&#39;;<br><br>export const appFeatureKey = &#39;app&#39;;<br><br>export interface State {<br>  books: BookModel[];<br>  selectedBook: BookModel;<br><br>}<br><br>export const initialState: State = {<br>  books: [<br>    {<br>      bookId: 1,<br>      bookName: &quot;Simyacı&quot;,<br>      author: &quot;Paulo Coelho&quot;<br>    },<br>    {<br>      bookId: 2,<br>      bookName: &quot;Suç ve Ceza&quot;,<br>      author: &quot;Fyodor Dostoyevski &quot;<br>    },<br>    {<br>      bookId: 3,<br>      bookName: &quot;Yeraltından Notlar&quot;,<br>      author: &quot;Fyodor Dostoyevski &quot;<br>    },<br>    {<br>      bookId: 4,<br>      bookName: &quot;Kürk Mantolu Madonna&quot;,<br>      author: &quot;Sabahattin Ali&quot;<br>    },<br>    {<br>      bookId: 5,<br>      bookName: &quot;Amok Koşucusu&quot;,<br>      author: &quot;Stefan Zweig&quot;<br>    }<br>    <br>  ],<br>  selectedBook: null<br>};<br><br><br>export const bookReducer = createReducer(<br>  initialState,<br>  on(AppActions.loadBooks, state =&gt; state),<br>  on(AppActions.addBook, (state, { book }) =&gt; {<br>    return {<br>      books: [...state.books, book],<br>      selectedBook: null<br>    }<br>  }),<br>  on(AppActions.selectBookById, (state, {bookId}) =&gt; {<br>    let sBook: BookModel = null;<br>    state.books.forEach(value =&gt; {<br>      if( value.bookId == bookId ) {<br>        return sBook = value;<br>      }<br>    })<br>    return {<br>      ...state,<br>      selectedBook: sBook<br>    }<br>  }),<br>  on(AppActions.deleteBook, (state, {id}) =&gt; {<br>    return {<br>      books: state.books.filter(book =&gt; book.bookId != id),<br>      selectedBook: null<br>    }<br>  }) <br><br>);</pre><p>export interface State ile gelecek verilerin ne olacağını belirtiyorum. interface ismi state olmak zorunda değil!</p><p>İnitialState ile uygulama ilk açıldığında yüklenmesini istediğim verileri veriyorum. Boş bırakabilirsiniz ben herhangi bir api den çekmeyeceğim için direk verdim.</p><p>Dikkat etmemiz gereken diğer bir nokta da her zaman yeni bir state oluşturduğumuz!</p><p>Şimdi de selectorler’i yazalım.</p><pre>import { createFeatureSelector, createSelector } from &#39;@ngrx/store&#39;;<br>import * as fromApp from &#39;./app.reducer&#39;;<br><br>export const selectAppState = createFeatureSelector&lt;fromApp.State&gt;(<br>  fromApp.appFeatureKey<br>);<br><br>export const selectBooks = createSelector(<br>  selectAppState,<br>  (state: fromApp.State) =&gt; state.books<br>);<br><br>export const selectSelectedBook = createSelector(<br>  selectAppState,<br>  (state: fromApp.State) =&gt; state.selectedBook<br>)</pre><p>Buraya kadar state’i oluşturduk şimdi componentlerimizi oluşturalım. Ardından componentler içerisinden nasıl tetikleyeceğimize bakalım.</p><p>Store’a erişebilmek için Store servisi ts dosyama dahil ediyorum. Store observable olduğu için pipe kullanabiliyorum.</p><p>Şimdi book-list.component.ts dosyamızı düzenleyelim.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { select, Store } from &#39;@ngrx/store&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { selectBooks } from &#39;../+state/app.selectors&#39;;<br>import { BookModel } from &#39;../models/bookModel&#39;;<br>import { State } from &#39;../+state/app.reducer&#39;;<br>@Component({<br>  selector: &#39;app-book-list&#39;,<br>  templateUrl: &#39;./book-list.component.html&#39;,<br>  styleUrls: [&#39;./book-list.component.css&#39;]<br>})<br>export class BookListComponent implements OnInit {<br><br>  bookList$: Observable&lt;BookModel[]&gt;;<br><br>  constructor(<br>    private store: Store&lt;State&gt;<br>  ) {}<br><br>  ngOnInit(): void {<br>    this.bookList$ = this.store.pipe(select(selectBooks));<br>  <br>  }<br><br>}</pre><p>book-list componenti içerisinde çıktı vermek için book-list.component.html dosyamı aşağıdaki gibi düzenliyorum.</p><p>Burada dikkat etmeniz gereken nokta state’ten gelen bilgiler observable olarak geliyor. Burdan gelen bilgileri yazdırmak için async pipe’ını kullanmayı unutmayın.</p><pre>&lt;table class=&quot;table&quot;&gt;<br>    &lt;thead&gt;<br>      &lt;tr&gt;<br>        &lt;th scope=&quot;col&quot;&gt;Book ID&lt;/th&gt;<br>        &lt;th scope=&quot;col&quot;&gt;Book Name&lt;/th&gt;<br>        &lt;th scope=&quot;col&quot;&gt;Author&lt;/th&gt;<br>        &lt;th scope=&quot;col&quot;&gt;&lt;/th&gt;<br>      &lt;/tr&gt;<br>    &lt;/thead&gt;<br>    &lt;tbody&gt;<br>      &lt;tr *ngFor=&quot;let book of bookList$ | async&quot;&gt;<br>        &lt;th scope=&quot;row&quot;&gt;{{book.bookId}}&lt;/th&gt;<br>        &lt;td&gt;{{book.bookName}}&lt;/td&gt;<br>        &lt;td&gt;{{book.author}}&lt;/td&gt;<br>        &lt;td&gt;<br>            &lt;button [routerLink]=&quot;[&#39;delete-book&#39;, book.bookId]&quot; class=&quot;btn btn-outline-danger&quot;&gt;Delete&lt;/button&gt;<br>        &lt;/td&gt;<br>      &lt;/tr&gt;<br>    &lt;/tbody&gt;<br>  &lt;/table&gt;<br><br>  &lt;button [routerLink]=&quot;[&#39;/add-book&#39;]&quot;  class=&quot;btn btn-outline-success&quot;&gt;ADD NEW BOOK&lt;/button&gt;</pre><p>Aşağıda gördüğünüz üzere çıktımız hazır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*zPujFPCPi1WaeY_S.png" /></figure><p>Artık state içerisindeki kitapları alıp listeleyebiliyorum.</p><p>Hadi şimdi yeni kitap ekleme kısımına geçelim.</p><p>Aşağıda add-book.component.ts dosyamız mevcut. ReactiveFormsModule ‘ü app.module.ts ‘e eklemeyi unutmayın. dispatch ile addBook action’ı tetikliyorum. Yazdığımız state/app.action.ts dosyasında 10.satıra bakarsanız orada props ta istediğimiz değeri component içerisinden veriyoruz. Ardından kullanıcıyı anasayfaya yönlendiriyoruz.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormBuilder } from &#39;@angular/forms&#39;;<br>import {  Router } from &#39;@angular/router&#39;;<br>import { Store } from &#39;@ngrx/store&#39;;<br>import { addBook } from &#39;../+state/app.actions&#39;;<br>import { State } from &#39;../+state/app.reducer&#39;;<br><br>@Component({<br>  selector: &#39;app-add-book&#39;,<br>  templateUrl: &#39;./add-book.component.html&#39;,<br>  styleUrls: [&#39;./add-book.component.css&#39;]<br>})<br>export class AddBookComponent implements OnInit {<br><br>  bookAdd = this.fb.group({<br>    bookId : [&#39;&#39;],<br>    bookName: [&#39;&#39;],<br>    author: [&#39;&#39;]<br><br>  })<br><br>  constructor(<br>    private fb: FormBuilder,<br>     private router: Router,<br>     private store: Store&lt;State&gt;<br>     ) { }<br><br>  ngOnInit(): void {<br>  }<br>  saveBook(){<br>    this.store.dispatch(addBook({book: this.bookAdd.value }));<br>    this.router.navigateByUrl(&quot;/&quot;);<br><br>  }<br><br>}</pre><p>Aşağıda add-book.component.html dosyamız mevcut. Buraya kitap id’si, adı ve yazarı olarak 3 tane textbox koyuyorum. Buradaki değerlere erişmek için reactive forms kullanıyorum.</p><pre>&lt;form [formGroup]=&quot;bookAdd&quot;&gt;<br>ID: &lt;input type=&quot;text&quot; class=&quot;form-control&quot; formControlName=&quot;bookId&quot;  /&gt;<br>Book Name: &lt;input type=&quot;text&quot; class=&quot;form-control&quot; formControlName=&quot;bookName&quot;/&gt;<br>Author: &lt;input type=&quot;text&quot; class=&quot;form-control&quot; formControlName=&quot;author&quot; /&gt;<br>&lt;button  (click)=&quot;saveBook()&quot; class=&quot;btn btn-outline-primary&quot;&gt;Save&lt;/button&gt;<br>&lt;/form&gt;</pre><p>Bunu da hallettikten sonra kitap silme işlemini yapalım. delete-book componentime geliyorum. Silmeden önce hangi kitabın silineceğini kullanıcıya gösteriyorum. Delete butonuna tıklayınca confirm çıkıyor. Eğer yanıtı evet olursa kitabı siliyoruz.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormBuilder } from &#39;@angular/forms&#39;;<br>import { ActivatedRoute, Router } from &#39;@angular/router&#39;;<br>import { select, Store } from &#39;@ngrx/store&#39;;<br>import { deleteBook, selectBookById } from &#39;../+state/app.actions&#39;;<br>import { State } from &#39;../+state/app.reducer&#39;;<br>import { selectSelectedBook } from &#39;../+state/app.selectors&#39;;<br><br>@Component({<br>  selector: &#39;app-delete-book&#39;,<br>  templateUrl: &#39;./delete-book.component.html&#39;,<br>  styleUrls: [&#39;./delete-book.component.css&#39;]<br>})<br>export class DeleteBookComponent implements OnInit {<br>  bookId;<br>  deleteForm = this.fb.group({<br>    bookId: [&#39;&#39;],<br>    bookName: [&#39;&#39;],<br>    author: [&#39;&#39;]<br>  });<br><br>  constructor(<br>    private activatedRoute: ActivatedRoute,<br>    private router: Router,<br>    private store: Store&lt;State&gt;,<br>    private fb: FormBuilder<br>  ) { }<br><br>  ngOnInit(): void {<br>    this.bookId = this.activatedRoute.snapshot.params.id;<br>    this.store.dispatch(selectBookById({bookId: this.bookId}));<br>    this.store.pipe(select(selectSelectedBook)).subscribe(value =&gt; {<br>      this.deleteForm.setValue({<br>        bookId: value.bookId,<br>        bookName: value.bookName,<br>        author: value.author<br>      });<br><br>    })<br><br>  }<br>  delete() {<br>    let checkStatus = confirm(&quot;Kitap silinecek emin misiniz?&quot;)<br>    if(checkStatus) {<br>      this.store.dispatch(deleteBook({id: this.bookId}));<br>      this.router.navigateByUrl(&quot;/&quot;);<br>    } else {<br>      this.router.navigateByUrl(&quot;/&quot;);<br>    }<br>    <br>  }<br><br>}</pre><p>Aşağıda delete-book.component.html dosyamız mevcut.</p><pre>&lt;form [formGroup]=&quot;deleteForm&quot;&gt;<br>    ID: &lt;input type=&quot;text&quot; class=&quot;form-control&quot; formControlName=&quot;bookId&quot; disabled=&quot;true&quot;/&gt;<br>    Book Name: &lt;input type=&quot;text&quot; class=&quot;form-control&quot; formControlName=&quot;bookName&quot;/&gt;<br>    Author: &lt;input type=&quot;text&quot; class=&quot;form-control&quot; formControlName=&quot;author&quot;/&gt;<br>    &lt;button  class=&quot;btn btn-outline-danger&quot; (click)=&quot;delete()&quot;&gt;Delete&lt;/button&gt;<br> &lt;/form&gt;</pre><p>Son olarak çıktımızı da aşağıda görüyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*mH5YJierrvjFK1G_.png" /></figure><p>Bu güzel yazımızda bizimle birlikte olduğunuz için teşekkürler. Öğrenmek sonu gelmeyen bir bilgi edinme’dir. Bilgilerinizin artması dileğiyle. Hoşça kalın:)</p><h4>Kaynaklar</h4><ul><li><a href="https://ngrx.io/">NgRx Docs</a></li><li><a href="https://www.npmjs.com/package/@ngrx/store">@ngrx/store</a></li><li><a href="https://sametcelikbicak.com/angular-ile-ngrx-kullanimi">Angular ile NGRX kullanımı</a></li><li><a href="https://www.workingsoftware.dev/what-is-ngrx-and-why-is-it-used-in-angular/">What is NgRx and why is it used in Angular apps?</a></li><li><a href="https://ichi.pro/tr/redux-icin-crash-course-98889338959570">Redux için Crash Course</a></li><li><a href="https://github.com/okanyesil/medium-yazi/tree/ngrx/todoApp/todoApp/src/app/book-list">medium-yazi/todoApp/todoApp/src/app/book-list at ngrx · okanyesil/medium-yazi</a></li><li><a href="https://okanyesiloglu.medium.com/angular-ngrx-kullan%C4%B1m%C4%B1-fe582e71fe7b">Angular NgRX Kullanımı</a></li><li><a href="https://www.gencayyildiz.com/blog/angular-ngrx-kutuphanesi-ile-state-management/">Angular - NgRx Kütüphanesi İle State Management</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=946ca07cfe37" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>