Angular 5 GET request nonresponsive

2019-08-20 04:42发布

问题:

I've seen many similar problems regarding this problem on this site, but they tend to be either too specific (with Django, Python, Spring, etc) or too outdated.

I am using Angular 5 and Bootstrap, using Chrome to debug, and my GET request does not GET, or give me any errors, or do anything, really. With zero output, I am not sure what I'm doing wrong.

My .ts file code:

onNameKeyUp(event:any) {
  this.id = event.target.value; //sets input to the object's id
  this.found = false;
}

getProf() {
this.httpClient.get(`api_url/${this.id}`)
.subscribe(
  (data:any[]) => {
    if(data.length) {
      this.name = data[0].name;
      this.id = data[0].id;
      this.found = true;
      }
    }
  )
}

My component.html code:

  <input type="text" (keyup)="onNameKeyUp($event)">
  <button type="button" (click)="getProf()">Get Profile</button>

  <div *ngIf="found">
    <div>{{this.name}}'s id is {{this.id}}</div>
  </div>

回答1:

replace this.name with name and this.id with id in your HTML



回答2:

Add error => to see the error, and then from there debug. You should see in your network tab if 404, 500, 200 etc.

this.httpClient.get(`api_url/${this.id}`)
    .subscribe(
      (data:any[]) => {
        if(data.length) {
          this.name = data[0].name;
          this.id = data[0].id;
          this.found = true;
          }
        },
        error => {
          console.log('See Error: ', error);
         }

         )


回答3:

In your code, data is an array and is a type of class or interface. I would define a profile of that type above your constructor like so,

profile: any;
constructor(...) {}

If you are getting a valid data:

  if(data.length) {
    this.name = data[0].name;
    this.id = data[0].id;
    this.found = true;
    console.log(data); // ---------> this should be an array (F12 developers tool).
     this.profile = data[0]; // should not give you an exception error.
  }
}

Then in you html code.

 <div *ngIf="found">
   <div>{{profile?.name}}'s id is {{profile?.id}}</div>
 </div>

? -* Don't forget to include this. If this does not work, let me know and I'd be happy to help. Happy coding..