Angular - передача объекта Json дочернему элементу с отображением [Object Object] - PullRequest
0 голосов
/ 17 мая 2018

Я делаю простой вызов API.Мой файл компонента ввода имеет следующий код:

Input.html

<form (submit)="getTransactions()">
  <div class="form-group">
    <label for="exampleInputEmail1"></label>
    <input type="text" class="form-control"  [(ngModel)]="address" name="address" placeholder="Bitoin Address">
    <button type="submit" class="btn btn-primary">Submit</button>
    {{address}}
  </div>
</form>

<app-display [address]="transactions"></app-display>

input.ts

export class InputComponent implements OnInit {

  address = "3MvuMn4CESuvA89bfA1cT8mgC4JtKaReku";
  transactions = [];

  constructor(private blockchain: BlockchainService) { }

  ngOnInit() {
  }

  submit(){
    console.log(this.address)
  }

  getTransactions(){
    this.blockchain.getTransactions().subscribe((data) => {
      // console.log(data.json())
      this.transactions = data.json();
      console.log(this.transactions)
    });
  }

}

Когда я console.log проверю, чтобы убедиться, чтоjson объект отображается правильно в моем компоненте Input, он работает.

Когда я console.log в моем компоненте Display, я вижу «[объект Object]».Ошибка не печатается.

Спасибо, ребята, это будет для меня точкой обучения.

display.htlm

<button (click)="hello()"></button>

display.ts

export class DisplayComponent implements OnInit {

  @Input() address = [];

  constructor(private blockchain: BlockchainService) { }

  ngOnInit() {
  }

  hello(){
    console.log(`data ${this.address}`);
  }

}

service.ts

@Injectable()
export class BlockchainService {

  baseurl: string = "http://localhost:4200/assets/info.json"

  constructor(private http: Http) { }

  getTransactions(){
    return this.http.get(this.baseurl);
  }

}

Ответы [ 2 ]

0 голосов
/ 17 мая 2018

вам нужно проанализировать объект json (address) в вашем DisplayComponent компоненте.

export class DisplayComponent implements OnInit {

  @Input() address: any;

  constructor(private blockchain: BlockchainService) { }

  ngOnInit() {
this.address  = JSON.parse(this.address);
  }

  hello(){
    console.log(`data ${this.address}`);
  }

}

как вы применили .json() метод в вашем компоненте ввода

0 голосов
/ 17 мая 2018

этот код может вам помочь

   this.blockchain.getTransactions().subscribe(
                        (data => {
                            if (data['status'] == 200) {
                                this.transactions = JSON.parse(data["_body"]);
}
    }),
                        error => this.toastr.error('Something went wrong !!', 'Oops!',{showCloseButton: true})
                    );

или отредактировать это в вашем сервисе

return this._http.get("your path").map(data => data.json())

this.blockchain.getTransactions().subscribe(
                            (data => {
                                if (data) {
                                    this.transactions = data;
    }
        }),
                            error => this.toastr.error('Something went wrong !!', 'Oops!',{showCloseButton: true})
                        );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...