相关疑难解决方法(0)

如何从异步调用返回响应?

我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo

我尝试从success回调中返回值,并将响应分配给函数内部的局部变量并返回该变量,但这些方法都没有实际返回响应.

function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            result = response;
            // return response; // <- I tried that one as well
        }
    });

    return result;
}

var result = foo(); // It always ends up being `undefined`.
Run Code Online (Sandbox Code Playgroud)

javascript ajax jquery asynchronous xmlhttprequest

5208
推荐指数
38
解决办法
134万
查看次数

如何让程序等待 Angular 中的 observable 执行

我正在开发一个有角度的项目,我遇到了使用可观察对象调用后端来获取产品的情况。

代码如下所示。

getProducts () : Product[] {
this.http.get<[]>(this.m_baseURL+'/products').subscribe(res => {
  console.log(res)
  this.products = res;
});
  return this.products
}
Run Code Online (Sandbox Code Playgroud)

问题是,return 语句不会等待上述语句执行。在我的组件中,我得到一个空数组。我在服务和组件中使用控制台日志进行了检查。事实证明,return 语句是在 observable 完成赋值之前执行的。

我如何让它停止直到完成其工作,就像 async wait 一样。我应该使用普通的异步等待而不是可观察的吗?

这是我的第一个 Angular 项目,所以如果问题是新手,请原谅我。

async-await angular2-observables angular

8
推荐指数
2
解决办法
3万
查看次数

打字稿获取当前位置并传递给后端以获取结果并传递给材料表数据源

我有我的 Angular 2 项目试图获取用户的当前位置,因此在我的班级中我有以下代码:

export class CurrentLocation {
  constructor(private http: Http) { }
  private lat : any;
  private lon : any;
  private params  = new URLSearchParams();
  private url = 'api/search/location';


  getPosition = (lat, lon) => {
    navigator.geolocation.getCurrentPosition((position) => { 
      this.lat = position.coords.latitude; 
      this.lon = position.coords.longitude;
     });
  }
  getCurrentLocation(): Observable<any> {
    this.getPosition(this.lat, this.lon);
    console.log(this.lat+ "," + this.lon);
    //console.log(this.lat + ":" + this.lon);
    this.params.set('lat', this.lat);
    this.params.set('lon', this.lon);
    //console.log(this.params.toString());
    var result = this.http.get(this.url, { search: this.params });
    result.toPromise();
    return result;
  }
}
Run Code Online (Sandbox Code Playgroud)

但是 …

typescript angular

5
推荐指数
1
解决办法
1万
查看次数

如何跟踪 Angular HTTP POST 调用进度

我试图在我的 http 调用中放置一个进度条,但是我无法发出同步 HTTP 调用请求,而是以异步方式进行。

下面是进行http调用的函数

 public authenticationt2cHTTP(email, password) {
    console.log("authenticationt2cHTTP WITH HEADERS");
    const body = new HttpParams()
      .set('email', email)
      .set('password', password);
    const req = new HttpRequest('POST', 'http://192.168.0.135:8080/rest/auth/login', body, {
      reportProgress: true,
      headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
    });

    this.http.request(req).subscribe(event => {
      // Via this API, you get access to the raw event stream.
      // Look for upload progress events.
      if (event.type === HttpEventType.UploadProgress) {
        // This is an upload progress event. Compute and show the % done:
        const percentDone = Math.round(100 …
Run Code Online (Sandbox Code Playgroud)

angular-cli angular

5
推荐指数
1
解决办法
5904
查看次数

Angular @input值未定义

将值从父级传递给子级.子组件中接收的值是未定义的工作示例

这是我的app.component

import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';

interface ItemsResponse {
  data: any[];
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
    constructor(private http: HttpClient) {}
  ngOnInit() {
    this.getPosts();
    console.log( this.name); // name is undefined
  }
  name;
  results:Array<any> = []; // code changed
    getPosts() {
        this.http.get<ItemsResponse>('https://reqres.in/api/users?page=3').subscribe(res =>
        this.name = res); // code changed
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的hello组件,其中数据被传递给子组件您可以看到在构造函数中未定义通过angular的@input装饰器从父组件传递到子组件的名称.

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello', …
Run Code Online (Sandbox Code Playgroud)

angular-cli angular

4
推荐指数
1
解决办法
3687
查看次数

为什么我必须调用 subscribe 才能运行我的 http 请求?

我正在使用 Angular 8 开发一个项目。我正在构建一个“忘记密码”页面,当用户单击提交按钮时,该页面将调用 2 个后端端点。

这是我的代码,但我没有任何可以公开的测试网址:https://stackblitz.com/edit/angular-8-app-example-zxzvt5

为了让我的 http 请求继续执行,我必须在此服务中调用它们的订阅:ForgotPasswordDataService

为什么我必须这么做?

如何更改我的代码,以便我不需要订阅,并且我想路由到组件中的下一页而不是我的服务?例如

  public onSubmit() {
    console.log(' on submit ');
    //submit to the server
    //route to the next page
    this.forgotPasswordDataService.forgotPassword(this.clientcode, this.email).subscribe(() => //TODO: route to the next page);
  }
Run Code Online (Sandbox Code Playgroud)

http observable angular

2
推荐指数
1
解决办法
1327
查看次数

Angular 2服务未更新到组件

我正在进行Service调用以从MongoDB获取数据.这部分似乎正在工作,它在控制台中正确记录.

这个响应非常大,可能需要大约8秒才能完全进入数据.为此,我希望能够data[]在检索到数据后更新组件.

我目前的解决方案不起作用,我想知道实时检索这个的正确和最佳实践.即使响应时间稍长.

服务调用getData

export class DataService {
dataArray: any[];
constructor(private http: Http){}

//get all data
getData(): any {
    console.log('Api is calling getData...');
    this.http.get('http://localhost:8080/api/data').map((res: Response) => res.json()).subscribe((res: any) => {
        this.dataArray = res;
   console.log('JSON: ' + this.dataArray);
   return this.dataArray;
 });
}
}
Run Code Online (Sandbox Code Playgroud)

这正确地导入MainComponent,没有错误.

MainComponent

export class MainComponent implements OnInit{
data: Array<any>;
//Inject service here to use for getting data
constructor(private dataService: DataService){}

ngOnInit(){
    //Set View Data with Request from Server
    this.data = this.dataService.getData();
    console.log("Data: " + this.data);
} …
Run Code Online (Sandbox Code Playgroud)

rxjs angular2-services angular

1
推荐指数
1
解决办法
659
查看次数

订阅调用后的空数组

我写了一个服务:

loadroom() : Observable<any[]>{
    return this.http.get(this.roomUrl)
        .pipe(
            map((response: any) => {
                let resources = response;
                return resources.map(function(room:any) {
                    return {id: room.id, title: room.title, eventcolor: room.eventColor};
                });
            })
        );
}
Run Code Online (Sandbox Code Playgroud)

然后我在一个组件中使用这个服务

rooms: any[] = [];       
ngOnInit() {
    this.schedulerService.loadroom().subscribe(response => this.rooms = response);
    console.log(this.rooms);
}
Run Code Online (Sandbox Code Playgroud)

我没有看到数组中的数据。在控制台中,我得到一个空数组 []

但如果我使用

this.schedulerService.loadroom().subscribe(response => {console.log(response)});
Run Code Online (Sandbox Code Playgroud)

我得到数据。

angular

0
推荐指数
1
解决办法
642
查看次数

在 angular 中成功调用订阅后未定义

我已经成功调用了 API 并从中调用了数据,但是如果我读取了变量,我会得到"Undefined"

调用api获取数据的服务类

export class DataServiceService {

   constructor(private http: Http) { }

   url: string = "http://localhost:60263/api/values";

   getEmployeesData(): Observable<EmployeeDetails[]> {
      return this.http.get(this.url).map((res: Response) => res.json());
   }
}
Run Code Online (Sandbox Code Playgroud)

订阅数据

export class AppComponent {

   emp: EmployeeDetails[];

   constructor(private dataServe: DataServiceService) { }

   ngOnInit() {
     this.dataServe.getEmployeesData().subscribe(res => this.emp = res);
   }

   clEmployeesCount: Number = this.emp.length; **Getting undefined here**
   clShowEmployee: boolean = false;
   clCreateEmployee: boolean = false;
}
Run Code Online (Sandbox Code Playgroud)

但是这在 HTML 部分工作正常

<div *ngIf="emp">
  <ul *ngFor="let user of emp">
   <li>{{user.ID}}</li>
 </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

typescript angular

-1
推荐指数
1
解决办法
9708
查看次数