如何解决从 observable 获取数据的问题

Posted

技术标签:

【中文标题】如何解决从 observable 获取数据的问题【英文标题】:How to resolve getting data from observable 【发布时间】:2021-09-14 14:46:59 【问题描述】:

当我在方法中使用 subscribe 时,我从 observable 获取数据时遇到问题 示例:

this.service.getProducts().subscribe(.....) , 

它返回给我: 从源“http://localhost:4200”访问“http://localhost:3011/clinic/products”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”

数据未列出

数据服务

import  Injectable  from '@angular/core';
import  HttpClient  from '@angular/common/http';
import  Product  from '../models/product.model';


@Injectable(
  providedIn: 'root'
)
export class DataService 

  public url = 'http://localhost:3010';
    
    constructor(private http: HttpClient)     

    getProducts()
        debugger;
        return this.http.get<Product[]>(`$this.url/clinic/products`);
    

    authenticate(data)
      return this.http.post(`$this.url/accounts/authenticate`,data);
    

    saveProducts(data)
      debugger;
      return this.http.post(`$this.url/clinic/products`,data);
    

        
    
  

产品页面

import  Component, OnInit  from '@angular/core';
import  FormBuilder, FormGroup  from '@angular/forms';
import  Router  from '@angular/router';
import  ToastrService  from 'ngx-toastr';
import  $  from 'protractor';
import  Observable  from 'rxjs';
import  Product  from 'src/app/models/product.model';
import  DataService  from 'src/app/services/data.services';
import  v4 as uuidv4  from 'uuid';


@Component(
  selector: 'app-products-page',
  templateUrl: './products-page.component.html',
  styleUrls: ['./products-page.component.css']
)
export class ProductsPageComponent implements OnInit 
  public products$!: Observable<Product[]>;
  public form: FormGroup;
  public prodId: string = uuidv4();
    

  constructor(
    private service: DataService,
    private fb: FormBuilder,
    private toastr: ToastrService,
    private router: Router
    )  
      this.form = this.fb.group(
        prodName:['', ],
        prodId:[this.prodId, ],
        slug:[this.prodId,],
        prodBrand: ['', ],
        prodMeasurement: ['',],
        prodAmount: ['',],
        prodVolume: ['',],
        prodWeight: ['',],
        prodPrice: ['',],
        prodActive:[true,]
 
      );
    

  ngOnInit(): void 
    this.products$ = this.service.getProducts();    

  

  submit()
    debugger;
    this.service.saveProducts(this.form.value)
        .subscribe(
          (data: any) => 
            this.toastr.success(data.message,'Teste');            
           
            debugger;
            let modalProducts = document.getElementById('modalProducts');
            modalProducts.hidden = true;
            this.router.navigate['/clinic/products'];
            this.ngOnInit();
          ,
          (err) => 
            console.log(err);
          
        );
    
      
  


API 发送的 JSON


    "dados":
        "Filial":"teste",
        "Cnpj":"12345678901234"
    ,
    "produtos": [
        
            "prodName": "Creme 02",
            "prodBrand": "Mary Kay",
            "prodMeasurement": "unidade",
            "prodAmount": "1",
            "prodVolume": "",
            "prodWeight": "",
            "prodPrice": "150"
        ,
        
            "prodName": "Creme 03",
            "prodBrand": "Mary Kay",
            "prodMeasurement": "unidade",
            "prodAmount": "1",
            "prodVolume": "",
            "prodWeight": "",
            "prodPrice": "154"
        ,
        
            "prodName": "Creme 05",
            "prodBrand": "Mary Kay",
            "prodMeasurement": "unidade",
            "prodAmount": "1",
            "prodVolume": "",
            "prodWeight": "",
            "prodPrice": "565"
        
    ]

【问题讨论】:

您认为服务器是否设置了适当的 CORS 标头? 您必须在后端代码中允许 CORS。 当我只尝试 this.products= this.service.getProducts();没有订阅这个错误不会发生,但我不能得到“产品” 使用邮递员也不会发生错误并正确返回数据 【参考方案1】:
@crossOrigin = (origins = "http://localhost:4200")

在服务类中,您使用的端口“3011”

【讨论】:

以上是关于如何解决从 observable 获取数据的问题的主要内容,如果未能解决你的问题,请参考以下文章

如何从 ngrx 存储中获取数据并将其更新到 Observable 变量中?

如何过滤 Observable 数组?

如何将Observable设置为void?

Angular 5 GET data with Observable and HttpClient - 从 Web API 获取数据

如何从使用 RxSwift 返回 Observable 的服务中获取值

如何从 Observable Array 嵌套对象中获取值