简体   繁体   English

Angular 订阅 function 未触发

[英]Angular subscribe function not being triggered

I have a "Login Component" that initializes variables as:我有一个“登录组件”,将变量初始化为:

  ngOnInit() {
    console.log("at ngOnInit");
    this.httpClientService.getUsers().subscribe(
      response =>{
        console.log("at subscribe");
        this.handleSuccessfulResponse(response);
      }
    );
    console.log(this.Users);
  }

  handleSuccessfulResponse(response)
  {   
    console.log("handle");
    this.Users=response;
    console.log(this.Users);
  }

getUsers() fucntion is as: getUsers() 函数如下:

  getUsers()
  { console.log("at  getUsers");

    return this.httpClient.get<User[]>('http://localhost:8080/findalluser');
  }

The URL http://localhost:8080/findalluser successfully returns: [{"id":"1001","username":"ariba","password":"abc"}] URL http://localhost:8080/findalluser成功返回:[{"id":"1001","username":"ariba","password":"abc"}]

When I login in to the UI with the credentials, I get an error with the following message on console:当我使用凭据登录 UI 时,我在控制台上收到错误消息并显示以下消息:

at ngOnInit
getUsers
undefined

and nothing else apart from the error that "this.Users is not iterable" which is justified because this.Users is undefined.除了“this.Users 不可迭代”的错误之外没有别的,这是合理的,因为 this.Users 是未定义的。 Apparently, the "subscribe()" function is not being triggered or maybe the httpClient isn't returning the Observable at all.显然,“subscribe()”function 没有被触发,或者 httpClient 根本没有返回 Observable。 I can't get why?我不明白为什么?

Update:更新:

Here's the whole Service code -这是整个服务代码 -

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';


import { stringify } from '@angular/compiler/src/util';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

export class Employee{
  constructor(
    public empId:string,
    public name:string,
    public designation:string,
    public salary:string,
  ) {}
}


export class User{
  constructor(
    public id:String,
    public username:string,
    public password:string,

  ) {}
}

export class UssdFiles{
  constructor(
    public filename:string,
    public filepath:string,
  ) {}
}

export class SmsFiles{
  constructor(
    public filename:string,
    public filepath:string,
  ) {}
}

export class Data{
  constructor( public flines: String )
  {}
}

export interface Post{
  id: number;
  userId: string;
  body: string;
  title: string;
}

@Injectable({
  providedIn: 'root'
})

export class HttpClientService {

  constructor(private httpClient:HttpClient) { }

  getUsers()
  {   console.log("getUsers");
    return this.httpClient.get<User[]>('http://localhost:8080/findalluser');
  }

  getUssdFiles(){
    return this.httpClient.get<UssdFiles[]>('http://localhost:8080/findallussd');
  }

  getSmsFiles(){
    return this.httpClient.get<SmsFiles[]>('http://localhost:8080/findallsms');
  }

  getFileData(file:String){
    //const str = JSON.stringify(this.httpClient.get<Data>('http://localhost:8080/getfiledata/'+file));
    return this.httpClient.get<Data>('http://localhost:8080/getfiledata/'+file);
  }

  postFileData(fileData:Object){
    console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
    console.log(fileData)
    return this.httpClient.post<Object>('http://localhost:8080/updatedfiledata',fileData).subscribe(response =>{
      console.log(response);
      //alert("File update successful!")
      if(response==null){
        alert("File update successful!");
      }
  })
  }

}

This is what I see in Network Tab on Devtools as I reload my Login page:这是我在重新加载登录页面时在 Devtools 的网络选项卡中看到的内容:网络选项卡

Try printing the data within the subscribe code itself,尝试在订阅代码本身中打印数据,

this.httpClientService.getUsers().subscribe((response) =>{
        console.log("at subscribe");
        console.log(response);
        this.Users=response;
      }
);

Since the subscription is an Async process is correct that printing this.Users in that part of the code gives you an undefined.由于订阅是一个Async过程是正确的,因此在该部分代码中打印this.Users会给您一个未定义的结果。

You should see logged that console.log("at subscribe");您应该看到记录了console.log("at subscribe"); tho.寿。

Put the console.log(this.Users);console.log(this.Users); inside the subscription after the function call在 function 调用之后的订阅内

this.handleSuccessfulResponse(response);

For the API not being called do you see the call in the network tab?对于没有被调用的 API,您在网络选项卡中看到调用了吗?

Try declaring users as an empty array to begin with instead of undefined.尝试将 users 声明为一个空数组,而不是 undefined。 Assuming you are using *ngFor in the DOM and undefined can't be iterated over.假设您在 DOM 中使用 *ngFor 并且 undefined 不能被迭代。

The HTTP request is async so it won't necessarily complete before the DOM renders. HTTP 请求是异步的,因此它不一定会在 DOM 呈现之前完成。 If you define users as a blank array it can iterate over this until your users come from server.如果您将用户定义为一个空白数组,则它可以对其进行迭代,直到您的用户来自服务器。

public users: Array<User> = [];

Try modifying your method like this尝试像这样修改您的方法

getUsers(): Observable<User[]>
{ 
  console.log("at  getUsers");
  return this.httpClient.get<User[]>('http://localhost:8080/findalluser');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM