如何在Angular5中获取对象?

时间:2018-04-11 06:57:59

标签: angular

我在Angular中获取数组时遇到问题。它只有在我单击按钮两次才能获得数组时才有效。我需要一次点击获取数据(参见页面末尾的Img)。

library(shiny)

# Define the UI
ui <- bootstrapPage(
  numericInput('s1', 'Share 1 (%):', 30, min = 5, max = 55),
  numericInput('s2', 'Share 2 (%):', 30, min = 5, max = 55),
  numericInput('s3', 'Share 3 (%):', 40, min = 5, max = 55),

  textOutput('result')
)


# Define the server code
server <- function(input, output) {
  output$result <- renderText({
    out <- input$s1 + input$s2 + input$s3
    validate(
      need(out <= 100, "The sum can't be over 100")
    )
    out
  })
}

# Return a Shiny app object
shinyApp(ui = ui, server = server)
@Injectable()
export class ConexionPersonService {

_people: Person[];

constructor(
    private http: HttpClient,
) { }

public getPeople(): void {

    const url = 'assets/Json/listPerson.json'; 
    this.http.get<Person[]>(url).subscribe(data => {this._people = data});
    console.log('ANTESobtenido ' , this._people);
}

public getPerson(id:number): Person{

    console.log('ID ' , id);

    if(this._people) {
        var per = this._people.find(person => person.id_user == id);
        console.log('obtenido ' , per);
        return this._people.find(person => person.id_user == id);
    }
}


}

所以问题是它第一次不起作用,但之后就可以了。

Img

2 个答案:

答案 0 :(得分:1)

实施不正确,可以更简单地看看以下解决方案:

<强>服务

export class DetailUserComponent implements OnInit { 
    detailPerson: Person;
    @Input() id;

    constructor(private service: ConexionPersonService) {}

    ngOnInit() {
        this.id = +this.route.snapshot.paramMap.get('id');
    }

    ngAfterViewInit() {
        this.getPerson();
    }

    getPerson(): void {  
        this.detailPerson = this.conexion.getPerson(this.id);      
    } 
}

<强>服务

@Injectable()
export class ConexionPersonService {
    _people: Person[];

    constructor(
        private http: HttpClient,
    ) { 
        this.getPeople();
    }

    public getPeople() {

        const url = 'assets/Json/listPerson.json';
        this.http.get<Person[]>(url).subscribe(data => this._people = data);
    }

    public getPerson(id:number): Person {

        if(this._people) {
            return this._people.find(person => person.id_user = id);
        }
    }
}

答案 1 :(得分:0)

当您检索人员列表(异步)时,获取特定人员的代码已经执行并返回null。

所以......要么在人员列表的订阅处理程序中更新特定人员的代码,要么让人们在ngOnInit上进行检索,并在按钮点击或ngAfterViewInit()上进行人员检索。

理想情况下,人员列表检索应该在服务自己的初始化(更好)中进行,或者可以通过直接链接两个请求来完成特定的人员搜索(从http获取人员列表并在成功处理程序中搜索id);虽然它会重复http调用(因此不是那么理想)。