简体   繁体   English

Angular GET http:// localhost / 401(未经授权)错误

[英]Angular GET http://localhost/ 401 (Unauthorized) error

I have a problem loading the user data into the page. 我在将用户数据加载到页面时遇到问题。 I get this Error: GET http://localhost/ 401 (Unauthorized). 我收到此错误:GET http:// localhost / 401(未经授权)。

In Laravel I've put this into my controller to get all user data: 在Laravel我把它放到我的控制器中以获取所有用户数据:

public function index()
{
 $user = User::all(); return response()->json($user,201);
}

In Angular I've created a data.service file with this code: 在Angular中,我使用以下代码创建了一个data.service文件:

@Injectable({
    providedIn: 'root'
})

export class DataService {
  constructor(private http: HttpClient) { }
  findAll(): Observable<User[]>{return this.http.get<User[]>('http://localhost');}
}

And In the app.component.ts file, I used this method to get the data: 在app.component.ts文件中,我使用此方法获取数据:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit{
  users$: User[];
  constructor(private dataService: DataService){}
  ngOnInit(){return this.dataService.findAll().subscribe(data => this.users$ = data);}
}

In the app.component.html file I've looped through the data: 在app.component.html文件中,我循环了数据:

<div *ngFor='let user of users$'>{{user.name}}</div>

Is this an error returned by angular or laravel? 这是由角或laravel返回的错误? Also please note the following: 另请注意以下事项:

  1. You're not specifying the port at localhost 您没有在localhost中指定端口
  2. You are defining user$ as an array not an observable, so the async pipe won't work, instead you can either declare user$ as an observable or remove the async pipe. 您将user $定义为不是可观察的数组,因此异步管道将无法工作,您可以将user $声明为observable或删除异步管道。

Here is the better solution: 这是更好的解决方案:

export class AppComponent implements OnInit{
  users$: Observable<User[]>;
  constructor(private dataService: DataService){}
  ngOnInit(){
    this.user$ = this.dataService.findAll()
  }
}

and in HTML keep your current code as it is: 并在HTML中保持您当前的代码:

<div *ngFor='let user of users$'>{{user.name}}</div>

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

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