Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

WikiQuora

WikiQuora Logo WikiQuora Logo

WikiQuora Navigation

Search
Ask A Question

Mobile menu

Close
Ask A Question
  • Home
  • Add group
  • Feed
  • User Profile
  • Communities
  • Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
Home/angular

WikiQuora Latest Questions

W3spoint99
  • 0
W3spoint99Begginer
Asked: January 17, 2025In: Angular

What is the difference between Promises and Observables?

  • 0

What is the difference between Promise and Observable in Angular? An example on each would be helpful in understanding both the cases. In what scenario can we use each case?

angularangular observableangular promisepromiserxjs
  1. Saralyn
    Saralyn Teacher
    Added an answer on January 17, 2025 at 2:03 pm

    Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature of our applications. The difference between them was pointed out clearly by Günter and @Relu. Since a code snippet is worth a thousand words, let’s go through the below example to understand theRead more

    Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature of our applications. The difference between them was pointed out clearly by Günter and @Relu.

    Since a code snippet is worth a thousand words, let’s go through the below example to understand them easier.

    Thanks @Christoph Burgdorf for the awesome article


    Angular uses Rx.js Observables instead of promises for dealing with HTTP.

    Suppose that you are building a search function that should instantly show you results as you type. It sounds familiar, but there are a lot of challenges that come with that task.

    • We don’t want to hit the server endpoint every time user presses a key. It should flood them with a storm of HTTP requests. Basically, we only want to hit it once the user has stopped typing instead of with every keystroke.
    • Don’t hit the search endpoint with the same query parameters for subsequent requests.
    • Deal with out-of-order responses. When we have multiple requests in-flight at the same time we must account for cases where they come back in unexpected order. Imagine we first type computer, stop, a request goes out, we type car, stop, a request goes out. Now we have two requests in-flight. Unfortunately, the request that carries the results for computer comes back after the request that carries the results for car.

    The demo will simply consist of two files: app.ts and wikipedia-service.ts. In a real world scenario, we would most likely split things further up, though.


    Below is a Promise-based implementation that doesn’t handle any of the described edge cases.

    wikipedia-service.ts

    import { Injectable } from '@angular/core';
    import { URLSearchParams, Jsonp } from '@angular/http';
    
    @Injectable()
    export class WikipediaService {
      constructor(private jsonp: Jsonp) {}
    
      search (term: string) {
        var search = new URLSearchParams()
        search.set('action', 'opensearch');
        search.set('search', term);
        search.set('format', 'json');
        return this.jsonp
                    .get('http://en.wikipedia.org/w/api.php?callback=JSONP_CALLBACK', { search })
                    .toPromise()
                    .then((response) => response.json()[1]);
      }
    }
    

    We are injecting the Jsonp service to make a GET request against the Wikipedia API with a given search term. Notice that we call toPromise in order to get from an Observable<Response> to a Promise<Response>. Eventually end up with a Promise<Array<string>> as the return type of our search method.

    app.ts

    // check the plnkr for the full list of imports
    import {...} from '...';
    
    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2>Wikipedia Search</h2>
          <input #term type="text" (keyup)="search(term.value)">
          <ul>
            <li *ngFor="let item of items">{{item}}</li>
          </ul>
        </div>
      `
    })
    export class AppComponent {
      items: Array<string>;
    
      constructor(private wikipediaService: WikipediaService) {}
    
      search(term) {
        this.wikipediaService.search(term)
                             .then(items => this.items = items);
      }
    }
    

    There is not much of a surprise here either. We inject our WikipediaService and expose its functionality via a search method to the template. The template simply binds to keyup and calls search(term.value).

    We unwrap the result of the Promise that the search method of the WikipediaService returns and expose it as a simple array of strings to the template so that we can have *ngFor loop through it and build up a list for us.

    See the example of Promise-based implementation on Plunker


    Where Observables really shine

    Let’s change our code to not hammer the endpoint with every keystroke, but instead only send a request when the user stopped typing for 400 ms

    To unveil such super powers, we first need to get an Observable<string> that carries the search term that the user types in. Instead of manually binding to the keyup event, we can take advantage of Angular’s formControl directive. To use this directive, we first need to import the ReactiveFormsModule into our application module.

    app.ts

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { JsonpModule } from '@angular/http';
    import { ReactiveFormsModule } from '@angular/forms';
    
    @NgModule({
      imports: [BrowserModule, JsonpModule, ReactiveFormsModule]
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    Once imported, we can use formControl from within our template and set it to the name “term”.

    <input type="text" [formControl]="term"/>
    

    In our component, we create an instance of FormControl from @angular/form and expose it as a field under the name term on our component.

    Behind the scenes, term automatically exposes an Observable<string> as property valueChanges that we can subscribe to. Now that we have an Observable<string>, overcoming the user input is as easy as calling debounceTime(400) on our Observable. This will return a new Observable<string> that will only emit a new value when there haven’t been coming new values for 400 ms.

    export class App {
      items: Array<string>;
      term = new FormControl();
      constructor(private wikipediaService: WikipediaService) {
        this.term.valueChanges
                  .debounceTime(400)        // wait for 400 ms pause in events
                  .distinctUntilChanged()   // ignore if next search term is same as previous
                  .subscribe(term => this.wikipediaService.search(term).then(items => this.items = items));
      }
    }
    

    It would be a waste of resources to send out another request for a search term that our application already shows the results for. All we have to do to achieve the desired behavior is to call the distinctUntilChanged operator right after we called debounceTime(400)

    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
2
  • 2 2 Answers
  • 527 Views
Answer
W3spoint99
  • 0
W3spoint99Begginer
Asked: January 17, 2025In: Angular

Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’?

  • 0

Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’? I have this simple input in my component which uses [(ngModel)] : <input type="text" [(ngModel)]="test" placeholder="foo" /> And I get the following error when I launch my app, even if the ...

angularangular formangular template form
  1. Saralyn
    Saralyn Teacher
    Added an answer on January 17, 2025 at 2:02 pm

    For using [(ngModel)] in Angular 2, 4 & 5+, you need to import FormsModule from Angular form... Also, it is in this path under forms in the Angular repository on GitHub: angular / packages / forms / src / directives / ng_model.ts Probably this is not a very pleasurable for the AngularJS developeRead more

    For using [(ngModel)] in Angular 2, 4 & 5+, you need to import FormsModule from Angular form…

    Also, it is in this path under forms in the Angular repository on GitHub:

    angular / packages / forms / src / directives / ng_model.ts

    Probably this is not a very pleasurable for the AngularJS developers as you could use ng-model everywhere anytime before, but as Angular tries to separate modules to use whatever you’d like you to want to use at the time, ngModel is in FormsModule now.

    Also, if you are using ReactiveFormsModule it needs to import it too.

    So simply look for app.module.ts and make sure you have FormsModule imported in…

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';  // <<<< import it here
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule, FormsModule // <<<< And here
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    
    export class AppModule { }
    

    Also, these are the current starting comments for Angular4 ngModel in FormsModule:

    /**
     * `ngModel` forces an additional change detection run when its inputs change:
     * E.g.:
     * ```
     * <div>{{myModel.valid}}</div>
     * <input [(ngModel)]="myValue" #myModel="ngModel">
     * ```
     * I.e. `ngModel` can export itself on the element and then be used in the template.
     * Normally, this would result in expressions before the `input` that use the exported directive
     * to have and old value as they have been
     * dirty checked before. As this is a very common case for `ngModel`, we added this second change
     * detection run.
     *
     * Notes:
     * - this is just one extra run no matter how many `ngModel` have been changed.
     * - this is a general problem when using `exportAs` for directives!
     */
    

    If you’d like to use your input, not in a form, you can use it with ngModelOptions and make standalone true…

    [ngModelOptions]="{standalone: true}"
    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
2
  • 2 2 Answers
  • 492 Views
Answer

Sidebar

Ask A Question
  • Popular
  • Answers
  • W3spoint99

    What is the difference between Promises and Observables?

    • 2 Answers
  • W3spoint99

    Can't bind to 'ngModel' since it isn't a known property ...

    • 2 Answers
  • W3spoint99

    How to prevent SQL injection in PHP?

    • 1 Answer
  • Saralyn
    Saralyn added an answer Learn Java if: ✅ You want to work on enterprise applications.… April 27, 2025 at 2:01 pm
  • Saralyn
    Saralyn added an answer AI is getting smarter, but replacing programmers entirely? That’s not… April 27, 2025 at 1:58 pm
  • Saralyn
    Saralyn added an answer Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature… January 17, 2025 at 2:03 pm

Trending Tags

AI angular application.properties arrays artificial intelligence coding how Java javascript machine learning mysql nullpointerexception php programmer python reactjs spring springboot sql string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

  • About US
  • Privacy Policy
  • Questions
  • Recent Questions
  • Web Stories

© 2025 WikiQuora.Com. All Rights Reserved