Angular 6 append value to Observable












1















messenger.component.ts



import { MessengerService } from 'messenger.service';

messages: any =;

ngOnInit(): void {
// call logs to http api
this.messages = this.messengerService.getData();
}

sendMessage(message){
this.messages.subscribe(data => {
data.push({
message_from: 'borrower',
message: message
});
console.log(data);
});
}



OUTPUT CONSOLE.LOG(data)



0: {message_from: "borrower", message: "hi", status: 0, user: 1}
1: {message_from: "borrower", message: "test", status: 0, user: 1}
2: {message_from: "borrower", message: "yea", status: 0, user: 1}
3: {message_from: "borrower", message: "aasd", status: 0, user: 1}
4: {message_from: "borrower", message: "aaa", status: 0, user: 1}



messenger.service.ts



public getData(): Observable<MessageData> {
return this.http.get<MessageData>('API', {
headers: {
Authorization: `Bearer ${sessionStorage.getItem('token')}`,
Accept: 'application/json'
}
}).pipe(map(response => response['success']));
}


messenger.component.html



<ng-container *ngFor="let message of messages | async ">
//template
</ng-container>


Already able fetch the data from Web server API. I want to add another function that sends data and able to show it as soon it clicks submit. How can do that using Observable, which ables to append to the previous list ?



Preview



I just wanted to show immediately the message after the function click sendMessage which will save through API and sync it with the Observable










share|improve this question




















  • 1





    Use Subject()/BehaviorSubject().

    – Jai
    Nov 23 '18 at 7:06











  • How are you sending the message data? What's the name of your service and the name of your Component? What method do you call when you submit from your Component?

    – SiddAjmera
    Nov 23 '18 at 7:15











  • @Jai can you please explain it further ?

    – marjorieasensi
    Nov 23 '18 at 7:16
















1















messenger.component.ts



import { MessengerService } from 'messenger.service';

messages: any =;

ngOnInit(): void {
// call logs to http api
this.messages = this.messengerService.getData();
}

sendMessage(message){
this.messages.subscribe(data => {
data.push({
message_from: 'borrower',
message: message
});
console.log(data);
});
}



OUTPUT CONSOLE.LOG(data)



0: {message_from: "borrower", message: "hi", status: 0, user: 1}
1: {message_from: "borrower", message: "test", status: 0, user: 1}
2: {message_from: "borrower", message: "yea", status: 0, user: 1}
3: {message_from: "borrower", message: "aasd", status: 0, user: 1}
4: {message_from: "borrower", message: "aaa", status: 0, user: 1}



messenger.service.ts



public getData(): Observable<MessageData> {
return this.http.get<MessageData>('API', {
headers: {
Authorization: `Bearer ${sessionStorage.getItem('token')}`,
Accept: 'application/json'
}
}).pipe(map(response => response['success']));
}


messenger.component.html



<ng-container *ngFor="let message of messages | async ">
//template
</ng-container>


Already able fetch the data from Web server API. I want to add another function that sends data and able to show it as soon it clicks submit. How can do that using Observable, which ables to append to the previous list ?



Preview



I just wanted to show immediately the message after the function click sendMessage which will save through API and sync it with the Observable










share|improve this question




















  • 1





    Use Subject()/BehaviorSubject().

    – Jai
    Nov 23 '18 at 7:06











  • How are you sending the message data? What's the name of your service and the name of your Component? What method do you call when you submit from your Component?

    – SiddAjmera
    Nov 23 '18 at 7:15











  • @Jai can you please explain it further ?

    – marjorieasensi
    Nov 23 '18 at 7:16














1












1








1








messenger.component.ts



import { MessengerService } from 'messenger.service';

messages: any =;

ngOnInit(): void {
// call logs to http api
this.messages = this.messengerService.getData();
}

sendMessage(message){
this.messages.subscribe(data => {
data.push({
message_from: 'borrower',
message: message
});
console.log(data);
});
}



OUTPUT CONSOLE.LOG(data)



0: {message_from: "borrower", message: "hi", status: 0, user: 1}
1: {message_from: "borrower", message: "test", status: 0, user: 1}
2: {message_from: "borrower", message: "yea", status: 0, user: 1}
3: {message_from: "borrower", message: "aasd", status: 0, user: 1}
4: {message_from: "borrower", message: "aaa", status: 0, user: 1}



messenger.service.ts



public getData(): Observable<MessageData> {
return this.http.get<MessageData>('API', {
headers: {
Authorization: `Bearer ${sessionStorage.getItem('token')}`,
Accept: 'application/json'
}
}).pipe(map(response => response['success']));
}


messenger.component.html



<ng-container *ngFor="let message of messages | async ">
//template
</ng-container>


Already able fetch the data from Web server API. I want to add another function that sends data and able to show it as soon it clicks submit. How can do that using Observable, which ables to append to the previous list ?



Preview



I just wanted to show immediately the message after the function click sendMessage which will save through API and sync it with the Observable










share|improve this question
















messenger.component.ts



import { MessengerService } from 'messenger.service';

messages: any =;

ngOnInit(): void {
// call logs to http api
this.messages = this.messengerService.getData();
}

sendMessage(message){
this.messages.subscribe(data => {
data.push({
message_from: 'borrower',
message: message
});
console.log(data);
});
}



OUTPUT CONSOLE.LOG(data)



0: {message_from: "borrower", message: "hi", status: 0, user: 1}
1: {message_from: "borrower", message: "test", status: 0, user: 1}
2: {message_from: "borrower", message: "yea", status: 0, user: 1}
3: {message_from: "borrower", message: "aasd", status: 0, user: 1}
4: {message_from: "borrower", message: "aaa", status: 0, user: 1}



messenger.service.ts



public getData(): Observable<MessageData> {
return this.http.get<MessageData>('API', {
headers: {
Authorization: `Bearer ${sessionStorage.getItem('token')}`,
Accept: 'application/json'
}
}).pipe(map(response => response['success']));
}


messenger.component.html



<ng-container *ngFor="let message of messages | async ">
//template
</ng-container>


Already able fetch the data from Web server API. I want to add another function that sends data and able to show it as soon it clicks submit. How can do that using Observable, which ables to append to the previous list ?



Preview



I just wanted to show immediately the message after the function click sendMessage which will save through API and sync it with the Observable







angular rest observable






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 10:37









Akber Iqbal

2,23731125




2,23731125










asked Nov 23 '18 at 7:01









marjorieasensimarjorieasensi

146




146








  • 1





    Use Subject()/BehaviorSubject().

    – Jai
    Nov 23 '18 at 7:06











  • How are you sending the message data? What's the name of your service and the name of your Component? What method do you call when you submit from your Component?

    – SiddAjmera
    Nov 23 '18 at 7:15











  • @Jai can you please explain it further ?

    – marjorieasensi
    Nov 23 '18 at 7:16














  • 1





    Use Subject()/BehaviorSubject().

    – Jai
    Nov 23 '18 at 7:06











  • How are you sending the message data? What's the name of your service and the name of your Component? What method do you call when you submit from your Component?

    – SiddAjmera
    Nov 23 '18 at 7:15











  • @Jai can you please explain it further ?

    – marjorieasensi
    Nov 23 '18 at 7:16








1




1





Use Subject()/BehaviorSubject().

– Jai
Nov 23 '18 at 7:06





Use Subject()/BehaviorSubject().

– Jai
Nov 23 '18 at 7:06













How are you sending the message data? What's the name of your service and the name of your Component? What method do you call when you submit from your Component?

– SiddAjmera
Nov 23 '18 at 7:15





How are you sending the message data? What's the name of your service and the name of your Component? What method do you call when you submit from your Component?

– SiddAjmera
Nov 23 '18 at 7:15













@Jai can you please explain it further ?

– marjorieasensi
Nov 23 '18 at 7:16





@Jai can you please explain it further ?

– marjorieasensi
Nov 23 '18 at 7:16












2 Answers
2






active

oldest

votes


















1














Completely untested, but the idea is that you use a BehaviourSubject which holds your new user inputted data. Which will be merged onSubmit and send to the this.messages using combineLatest. While on loading of the component it gets the messages from the service.



newMessages = new BehaviourSubject<MessageData>();

messages: Observable<MessageData> = combineLatest(
this.newMessages,
this.messengerService.getData()
).pipe(
map(([added, data]) => data.concat(added))
);

sendMessage(message): void {
const messages = this.newMessages.getValue();
messages.push(message);

this.newMessages.next(messages);
this.messengerService.addMessage({
message_from: 'borrower',
message
}); // make proper sending logic here
}





share|improve this answer


























  • Is it possible to add an (static) array item in an existing Observable<MessageData>

    – marjorieasensi
    Nov 23 '18 at 8:58













  • @marjorieasensi No.

    – PeS
    Nov 23 '18 at 9:06











  • @PierreDuc - how about converting the array to Observable ? Have you check my updated questions ?

    – marjorieasensi
    Nov 23 '18 at 9:10













  • @marjorieasensi my solution immediately updates the array, and also updates the view, without the need to wait for the saving of the message

    – PierreDuc
    Nov 23 '18 at 9:13



















0














If I true understand you question you can use this method



currentTook = new BehaviorSubject();


in get request



    this.currentTook.next(sendData);


and in another component you can input this



@Input() currentTook: Observable<any>;

this.currentTook.subscribe(data => {
console.log(data);

});





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53442002%2fangular-6-append-value-to-observable%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Completely untested, but the idea is that you use a BehaviourSubject which holds your new user inputted data. Which will be merged onSubmit and send to the this.messages using combineLatest. While on loading of the component it gets the messages from the service.



    newMessages = new BehaviourSubject<MessageData>();

    messages: Observable<MessageData> = combineLatest(
    this.newMessages,
    this.messengerService.getData()
    ).pipe(
    map(([added, data]) => data.concat(added))
    );

    sendMessage(message): void {
    const messages = this.newMessages.getValue();
    messages.push(message);

    this.newMessages.next(messages);
    this.messengerService.addMessage({
    message_from: 'borrower',
    message
    }); // make proper sending logic here
    }





    share|improve this answer


























    • Is it possible to add an (static) array item in an existing Observable<MessageData>

      – marjorieasensi
      Nov 23 '18 at 8:58













    • @marjorieasensi No.

      – PeS
      Nov 23 '18 at 9:06











    • @PierreDuc - how about converting the array to Observable ? Have you check my updated questions ?

      – marjorieasensi
      Nov 23 '18 at 9:10













    • @marjorieasensi my solution immediately updates the array, and also updates the view, without the need to wait for the saving of the message

      – PierreDuc
      Nov 23 '18 at 9:13
















    1














    Completely untested, but the idea is that you use a BehaviourSubject which holds your new user inputted data. Which will be merged onSubmit and send to the this.messages using combineLatest. While on loading of the component it gets the messages from the service.



    newMessages = new BehaviourSubject<MessageData>();

    messages: Observable<MessageData> = combineLatest(
    this.newMessages,
    this.messengerService.getData()
    ).pipe(
    map(([added, data]) => data.concat(added))
    );

    sendMessage(message): void {
    const messages = this.newMessages.getValue();
    messages.push(message);

    this.newMessages.next(messages);
    this.messengerService.addMessage({
    message_from: 'borrower',
    message
    }); // make proper sending logic here
    }





    share|improve this answer


























    • Is it possible to add an (static) array item in an existing Observable<MessageData>

      – marjorieasensi
      Nov 23 '18 at 8:58













    • @marjorieasensi No.

      – PeS
      Nov 23 '18 at 9:06











    • @PierreDuc - how about converting the array to Observable ? Have you check my updated questions ?

      – marjorieasensi
      Nov 23 '18 at 9:10













    • @marjorieasensi my solution immediately updates the array, and also updates the view, without the need to wait for the saving of the message

      – PierreDuc
      Nov 23 '18 at 9:13














    1












    1








    1







    Completely untested, but the idea is that you use a BehaviourSubject which holds your new user inputted data. Which will be merged onSubmit and send to the this.messages using combineLatest. While on loading of the component it gets the messages from the service.



    newMessages = new BehaviourSubject<MessageData>();

    messages: Observable<MessageData> = combineLatest(
    this.newMessages,
    this.messengerService.getData()
    ).pipe(
    map(([added, data]) => data.concat(added))
    );

    sendMessage(message): void {
    const messages = this.newMessages.getValue();
    messages.push(message);

    this.newMessages.next(messages);
    this.messengerService.addMessage({
    message_from: 'borrower',
    message
    }); // make proper sending logic here
    }





    share|improve this answer















    Completely untested, but the idea is that you use a BehaviourSubject which holds your new user inputted data. Which will be merged onSubmit and send to the this.messages using combineLatest. While on loading of the component it gets the messages from the service.



    newMessages = new BehaviourSubject<MessageData>();

    messages: Observable<MessageData> = combineLatest(
    this.newMessages,
    this.messengerService.getData()
    ).pipe(
    map(([added, data]) => data.concat(added))
    );

    sendMessage(message): void {
    const messages = this.newMessages.getValue();
    messages.push(message);

    this.newMessages.next(messages);
    this.messengerService.addMessage({
    message_from: 'borrower',
    message
    }); // make proper sending logic here
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 23 '18 at 12:56

























    answered Nov 23 '18 at 7:20









    PierreDucPierreDuc

    29.9k55878




    29.9k55878













    • Is it possible to add an (static) array item in an existing Observable<MessageData>

      – marjorieasensi
      Nov 23 '18 at 8:58













    • @marjorieasensi No.

      – PeS
      Nov 23 '18 at 9:06











    • @PierreDuc - how about converting the array to Observable ? Have you check my updated questions ?

      – marjorieasensi
      Nov 23 '18 at 9:10













    • @marjorieasensi my solution immediately updates the array, and also updates the view, without the need to wait for the saving of the message

      – PierreDuc
      Nov 23 '18 at 9:13



















    • Is it possible to add an (static) array item in an existing Observable<MessageData>

      – marjorieasensi
      Nov 23 '18 at 8:58













    • @marjorieasensi No.

      – PeS
      Nov 23 '18 at 9:06











    • @PierreDuc - how about converting the array to Observable ? Have you check my updated questions ?

      – marjorieasensi
      Nov 23 '18 at 9:10













    • @marjorieasensi my solution immediately updates the array, and also updates the view, without the need to wait for the saving of the message

      – PierreDuc
      Nov 23 '18 at 9:13

















    Is it possible to add an (static) array item in an existing Observable<MessageData>

    – marjorieasensi
    Nov 23 '18 at 8:58







    Is it possible to add an (static) array item in an existing Observable<MessageData>

    – marjorieasensi
    Nov 23 '18 at 8:58















    @marjorieasensi No.

    – PeS
    Nov 23 '18 at 9:06





    @marjorieasensi No.

    – PeS
    Nov 23 '18 at 9:06













    @PierreDuc - how about converting the array to Observable ? Have you check my updated questions ?

    – marjorieasensi
    Nov 23 '18 at 9:10







    @PierreDuc - how about converting the array to Observable ? Have you check my updated questions ?

    – marjorieasensi
    Nov 23 '18 at 9:10















    @marjorieasensi my solution immediately updates the array, and also updates the view, without the need to wait for the saving of the message

    – PierreDuc
    Nov 23 '18 at 9:13





    @marjorieasensi my solution immediately updates the array, and also updates the view, without the need to wait for the saving of the message

    – PierreDuc
    Nov 23 '18 at 9:13













    0














    If I true understand you question you can use this method



    currentTook = new BehaviorSubject();


    in get request



        this.currentTook.next(sendData);


    and in another component you can input this



    @Input() currentTook: Observable<any>;

    this.currentTook.subscribe(data => {
    console.log(data);

    });





    share|improve this answer




























      0














      If I true understand you question you can use this method



      currentTook = new BehaviorSubject();


      in get request



          this.currentTook.next(sendData);


      and in another component you can input this



      @Input() currentTook: Observable<any>;

      this.currentTook.subscribe(data => {
      console.log(data);

      });





      share|improve this answer


























        0












        0








        0







        If I true understand you question you can use this method



        currentTook = new BehaviorSubject();


        in get request



            this.currentTook.next(sendData);


        and in another component you can input this



        @Input() currentTook: Observable<any>;

        this.currentTook.subscribe(data => {
        console.log(data);

        });





        share|improve this answer













        If I true understand you question you can use this method



        currentTook = new BehaviorSubject();


        in get request



            this.currentTook.next(sendData);


        and in another component you can input this



        @Input() currentTook: Observable<any>;

        this.currentTook.subscribe(data => {
        console.log(data);

        });






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 7:13









        Boris AdamyanBoris Adamyan

        268




        268






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53442002%2fangular-6-append-value-to-observable%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Wiesbaden

            Marschland

            Dieringhausen