Xamarin:如何在web服务响应之前阻止导航到另一个页面

本文关键字:导航 另一个 web 响应 服务 Xamarin | 更新日期: 2023-09-27 18:00:19

我尝试调用web服务来检索将在下一页上显示的数据。但是,在完成web服务请求之前,页面试图显示空数据。你能帮我做这个吗。

//代码

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += async (s, e) =>
{                     
    getEmployeepage(mainContact.managerID);                 
    await Navigation.PushAsync(new ManagerDetailsPage(data()));             
};
manager.GestureRecognizers.Add(tapGestureRecognizer);

//检索数据的方法

public async void getEmployeepage(String searchvalue)
{
    EmployeeDetailsPage employeeDetailsPage = null;
    try
    { 
        var client = new System.Net.Http.HttpClient();
        client.BaseAddress = new Uri("http://..........");
        var response = await client.GetAsync("criterion?empId=" + searchvalue);
        string jsonString = response.Content.ReadAsStringAsync().Result;                   
        //rest of the logic            
    }
}

提前感谢。

Xamarin:如何在web服务响应之前阻止导航到另一个页面

您的方法应该是可重写的。因此public async void getEmployeepage(String searchvalue)变成public async Task getEmployeepage(String searchvalue)。有了这个,你可以这样等待你的方法:

await getEmployeepage(mainContact.managerID);

使用async属性扩展异步方法名称也是一种很好的做法。您的方法名称将更改为GetEmployeePageAsync。另一个好的做法是始终返回Task。从而使一种方法变得无用。此模式的唯一例外是事件处理程序。

您需要await异步调用,并将getEmployeepage方法从async void更改为async Task:

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += async (s, e) =>
{                     
    await getEmployeepage(mainContact.managerID);                 
    await Navigation.PushAsync(new ManagerDetailsPage(data()));             
};
manager.GestureRecognizers.Add(tapGestureRecognizer);

&

public async Task getEmployeepage(String searchvalue)
{
    EmployeeDetailsPage employeeDetailsPage = null;
    try
    { 
        var client = new System.Net.Http.HttpClient();
        client.BaseAddress = new Uri("http://..........");
        var response = await client.GetAsync("criterion?empId=" + searchvalue);
        string jsonString = await response.Content.ReadAsStringAsync();                   
        //rest of the logic            
    }
}