при нажатии на функцию компонента A я хочу распечатать некоторые данные в компоненте B, используя сервис - PullRequest
0 голосов
/ 07 апреля 2020

с использованием git API. Я хочу получить введенный идентификатор пользователя, имя в текстовом поле.

У меня есть компонент A, в котором при нажатии кнопки я передаю git имя пользователя службе и на основе на том же компоненте я вызываю эту услугу и распечатываю детали в текстовом поле. Теперь я хочу сделать это с двумя компонентами, в компоненте ai есть текстовое поле, в котором будет вводиться имя пользователя и кнопка. Во втором компоненте я буду печатать детали. Теперь я не знаю, как передать эту информацию в компонент B, который я получаю по нажатию кнопки в компоненте A.

Компонент A

import { GituserdetailsService } from '../service/gituserdetails.service';
import { JsonPipe } from '@angular/common';
import { DetailsComponent } from '../details/details.component';


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

username:string ;
details:any;

  constructor(private GituserdetailsService:GituserdetailsService) { }

  ngOnInit(): void {

    //this.searchUserDetails();

  }
searchUserDetails() :void{
  this.details = [];
  this.GituserdetailsService.searchUser(this.username).subscribe((data: any[])=>{
    //console.log(data);
    this.details = data;

  })  ;
  //console.log(this.username);
}
}

Компонент B

import { GituserdetailsService } from '../service/gituserdetails.service';
@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {
details:any;

  constructor(private GituserdetailsService:GituserdetailsService) { }

  ngOnInit(): void {
  }

}

Сервис

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class GituserdetailsService {
   username:String;

  constructor(private http:HttpClient) { }

    searchUser(username:String) :Observable<any>
   {
     //console.log(`http://api.github.com/users/`+username);
    return this.http.get(`http://api.github.com/users/`+username)

}

}

1 Ответ

1 голос
/ 07 апреля 2020
    You would have to use `@Input ()` in angular to pass values between components

    An example would be 

    import{ GituserdetailsService } from '../service/gituserdetails.service';
    import { JsonPipe } from '@angular/common';
   import { Component } from '@angular/core';


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

    username:string ;
    details:any;

      constructor(private GituserdetailsService:GituserdetailsService) { }

      ngOnInit(): void {

        //this.searchUserDetails();

      }
    searchUserDetails() :void{
      this.details = [];
      this.GituserdetailsService.searchUser(this.username).subscribe((data: any[])=>{
        //console.log(data);
        this.details = data;

      })  ;
      //console.log(this.username);
    }
    }



    import { GituserdetailsService } from '../service/gituserdetails.service';
import { Component, Input } from '@angular/core';
    @Component({
      selector: 'app-details',
      templateUrl: './details.component.html',
      styleUrls: ['./details.component.css']
    })
    export class DetailsComponent implements OnInit {
    @Input() details:any;

      constructor(private GituserdetailsService:GituserdetailsService) { }

      ngOnInit(): void {
      }

    }


Then inside the HTML of ComponentA, you can have 

        <input type="text" > <button type="button">Click Me!</button>

        <componentB *ngIf="details" [details]="details"></ComponentB>

You can read more about it here https://angular.io/api/core/Input
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...