In the last post, I created a simple web app that can fetch and show data from Reddit, but it doesn’t have many features, only able to view threads from /r/worldnews. In this post I’m going to restructure the app a bit and add subreddit browsing feature.
Application structure
Right now my app has only one component - dashboard - in the app folder, which is difficult to scale if my app grows. So I’m going to create a components folder inside app, then move all created component in there.
After moving the component, I need to fix the import.
Next step, I will create a component for displaying subreddit, the command is similar to dashboard creation, but I need to prepend the folder name
1
ng generate component components/subreddit
Subreddit component has been generated in src/app/components/subreddit.
Services
So now we have dashboard for reddit front page, and subreddit for each subreddit page. Since the data fetching logic is the same (making a request, subscribe the thread list to response data etc), so only one service is needed.
I will rename dashboard service…
1
2
dashboard.service.spec.ts
dashboard.service.ts
…to common service (feel free to pick any name you like, just remember to update the source code with the correct name).
1
2
common.service.spec.ts
common.service.ts
If you are using Visual Code to rename, a pop up message will appear asking if you want VS Code to fix the import. In this post I’m going to do it manually.
common.service.ts
1
exportclassCommonService
common.service.spec.ts
1
2
3
4
5
6
7
8
9
10
import{CommonService}from'./common.service';describe('CommonService',()=>{beforeEach(()=>TestBed.configureTestingModule({}));it('should be created',()=>{constservice: CommonService=TestBed.get(CommonService);expect(service).toBeTruthy();});});
Currently in common service, there is only one function getThreads. The only difference between front page and subreddit is the URL. So I will make 2 more functions and call to getThreads.
Now we have dashboard component and subreddit component. The 2 components have almost the same logic: call to common service to fetch data from Reddit, then map data to list threads in view. We will create a child component called thread-list and use it in both dashboard and subreddit.
Now we need to call Common service from dashboard/subreddit, then pass the data into thread-list component. There are many ways to achieve this, I will use input binding since it’s pretty simple.
Here we bind “Go!” button’s click event to function toSubreddit. We also insert thread-list component into dashboard as a child component, bind threads property to thread-list’s threads property we created above.
Inside dashboard component logic, on init loadFrontpage will be called, if user clicks button, the app will call toSubreddit, then get value from textbox and redirect to subreddit component.