Skip to content Skip to sidebar Skip to footer

Angular 2 *ngFor And Form Submit Ceased Working When Moved To Observables

I had an app initiating course components like this:
  • Solution 1:

    Got it!

    The first issue was properly subscribing to the observable.

    ngOnInit() {
        this.appListService.getAppList()
        .subscribe(res => this.courses = res);
    }
    

    The App List Service is just acting as a manager in this case, so it is just returning an observable:

    constructor(private storage:CoursesService) { }
    getAppList() {
      return this.storage.get();
    }
    

    The Courses Service makes the GET request to the backend:

    get(): Observable<Course[]> {
        return this.http.get(this.BaseUrl)
                        .map((res:Response) => res.json())
                        .catch(this.handleError);
                        }
    

    When the resulting observable gets passed up to the main component, the ngFor works fine.

    Now, for the POST. First of all, I had to JSON.stringify() the body, like this:

    post(course: Course): Observable<Course[]> {
        let courseString = JSON.stringify(course);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post(this.BaseUrl, courseString, options)
                    .map((res:Response) => res.json())
                    .catch(this.handleError);
        }
    

    Then, I went on the back end and adjusted the POST so that instead of replying with a success message, it replied with the results of a general GET request.

    Now, everything works fine (except for all the work that remains to do, of course.)


  • Post a Comment for "Angular 2 *ngFor And Form Submit Ceased Working When Moved To Observables"