Home > Net >  Angular observable and service
Angular observable and service

Time:07-10

post-create.component.ts

import { Component, EventEmitter, Output} from "@angular/core";
import { NgForm } from "@angular/forms";
import { Post } from '../post.model';
import { PostsService } from "../posts.service";


 @Component({
    selector: 'app-post-create',
    templateUrl: './post-create.component.html',
    styleUrls: ['./post-create.component.css']
 })

export class PostCreateComponent {
    enteredContent = '';
    enteredTitle = '';

    constructor(public postsService: PostsService){}

    onAddPost(form: NgForm){
        if(form.invalid){
            return;
        }
        this.postsService.addPost(form.value.title, form.value.content);
        form.resetForm();
    }
}

posts.service.ts

import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
import { Post } from "./post.model";

@Injectable({
    providedIn: 'root'
})

export class PostsService {
    private posts: Post[]= [];

    getPosts(){
        return this.posts;
    }

    addPost(title: string, content: string){
        const post: Post = {title: title, content: content};
        this.posts.push(post);
    }
}

post-list.component.ts

import { Component, OnInit } from "@angular/core";
import { Post } from "../post.model";
import { PostsService } from "../posts.service";

 @Component({
    selector: 'app-post-list',
    templateUrl: './post-list.component.html' ,
    styleUrls: ['./post-list.component.css']
 })

export class PostListComponent implements OnInit {
    posts: Post[] = [];

    constructor(public postsService: PostsService){}

    ngOnInit(): void {
        this.posts = this.postsService.getPosts();
    }
 }

As you can see , I have not implemented observable to observe the change in post in service which is used in post-list.component.ts to display the list.I was under the impression that observable is required to look for the changes, however even without using observable as you see in code text above, it was working fine. How was it working without observable? ngOnInit at post-list.component.ts was running on each render? I used the console.log on ngOnInit at post-list.component.ts, it wasn't logging each time I created post, but list was getting rendered.

CodePudding user response:

How was it working without observable?

In your ngOnInit, you're assigning this.posts = this.postsService.getPosts(); (which amounts to this.posts = this.postsService.posts. Since posts is an object, this assignment creates not a copy, but simply another reference to the same object. Updating one, you're updating another, because another is the same object.

Consider trivial example:

const alice = { name: "Alice" };
const bob = alice;
bob.name = "Bob";

console.log(alice.name);

But this is not a good way of synchronizing values in Angular. One reason, it'll slip past detection if you use onPush change detection strategy. Another, the live link between the objects isn't obvious.

  • Related