I cannot post data to back end from angular6

269 views
Skip to first unread message

chinelo...@gmail.com

unread,
Oct 18, 2018, 7:19:24 AM10/18/18
to Angular and AngularJS discussion
Am trying to post data to php backend and display json call  response message success but am having the following errors


Error in src/app/car.service.ts(42,5): error type
observable<Object> is not assignable to type Observable<String>

Here is app.component.ts code

import { Component, OnInit } from '@angular/core';

import { Car } from './car';
import { CarService } from './car.service';
   



@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {


  //cars: Car[];


cars: Car="";



  error = '';
  success = '';

car = new Car('', 0);

  constructor(private carService: CarService) {
  }


  ngOnInit() {
    //this.getCars();
  }


public regCar(r) {
          this.resetErrors();
          this.carService.store1(this.car)
            .subscribe(
              res => {
                alert(res);

                if (res === 'success') { // or this.cars['message']
                    // Inform the user
                    this.success = 'Created successfully';
                }

                // Reset the form
                r.reset();
              },
              err => this.error = err
            );
    }

  private resetErrors(){
    this.success = '';
    this.error   = '';
  }

}


Here is the Car.services.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { Car } from './car';


@Injectable({
  providedIn: 'root'
})
export class CarService {



//cars: ;

//cars: Car[];

constructor(private http: HttpClient) { }

  store1(car: Car): Observable<String> {
    return this.http.post(`${this.baseUrl}/store1`, { data: car })
      .pipe(
      catchError(this.handleError));
  }

  private handleError(error: HttpErrorResponse) {
    console.log(error);

    // return an observable with a user friendly message
    return throwError('Error! something went wrong.');
  }
}



here is the car.ts

export class Car {
  constructor(
    model: string,
    price: number,
    id?:   number) {}
}



store.php


// pass parameter here
$car = [
      'message' => 'success'
    ];
 
    echo json_encode($car);
  }
  else
  {
    http_response_code(422);
  }







Riccardo Sadocchi

unread,
Oct 21, 2018, 10:12:39 AM10/21/18
to Angular and AngularJS discussion
Hi,
try to modify the return type of store1 function from Observable<string> to Observable<Car> or Observable<any>.
Reply all
Reply to author
Forward
Message has been deleted
0 new messages