Peter Penzov
Peter Penzov

Reputation: 1658

Empty result with GET request

I want to implement Angular example which gets list from rest API. I tried this:

SQL query:

    @Override
    public Iterable<Merchants> findAll() {
        String hql = "select e from " + Merchants.class.getName() + " e";
        TypedQuery<Merchants> query = entityManager.createQuery(hql, Merchants.class);
        List<Merchants> merchants = query.getResultList();
        return merchants;
    }

Rest controller:

@RestController
@RequestMapping("/merchants")
public class MerchantController {

    @GetMapping("/list")
    public Iterable<Merchants> getMerchantsList() {
        return merchantRepository
                .findAll();
    }
}

Service:

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

  constructor(private http: HttpClient) {
  }    
  getList() {
    return this.http.get("...../api/merchants/list");
  }
}

Component:

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

  constructor(private terminalService: TerminalService,
              private merchantService: MerchantService,
              private router: Router,
              private route: ActivatedRoute) {
  } 

  merchants: Merchant[];

  ngOnInit() {   
    this.merchantService.getList().pipe(
      flatMap(params => {
          return this.merchantService.getList();
      })
    ).subscribe(value => {
      if (value != null) {
        this.merchants = value;
      }
    });
  }
}

But I get error when I try to use the component:

ERROR in src/app/panel/terminal/terminal.component.ts(57,9): error TS2322: Type 'Object' is not assignable to type 'Merchant[]'.
  The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
src/app/panel/terminal/terminal.component.ts(57,9): error TS2322: Type 'Object' is not assignable to type 'Merchant[]'.
  The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
    Property 'includes' is missing in type 'Object'.

Can you give me some advice where I'm wrong? Probably my typescript is somewhere incorrect?

Upvotes: 2

Views: 319

Answers (1)

Wrokar
Wrokar

Reputation: 963

I have two suggestions which should address the issue. First, you are able to specify the return type of getList:

getList(): Observable<Merchant[]> {
  return this.http.get<Merchant[]>("...../api/merchants/list");
}

And second, I am not sure the flatMap operator is being used properly here. Unless you are specifically attempting to call the service again for each response, you can convert your call to:

this.merchantService.getList()
  .subscribe(value => {
    if (value != null) {
      this.merchants = value;
    }
  });

Upvotes: 2

Related Questions